1. 同步方法实现 //通过https加载json数据 let url = 'https://img-home.csdnimg.cn/data_json/toolbar/toolbar1105.json'; let GetJsonData=function (url){ const https = require('https'); https.get(url, (response) = { let data = ''; //数
1. 同步方法实现
//通过https加载json数据let url = 'https://img-home.csdnimg.cn/data_json/toolbar/toolbar1105.json';
let GetJsonData=function (url){
const https = require('https');
https.get(url, (response) => {
let data = '';
//数据正在接收中...
response.on('data', (chunk) => {
data += chunk;
});
//数据接收完成
response.on('end', () => {
console.log('同步请求数据完成:',JSON.parse(data));
});
}).on("error", (error) => {
console.log("Error: " + error.message);
});
}
加载数据
GetJsonData(url);加载结果
2.异步方法实现
//异步请求JSON数据实现let GetJsonDataAsync=(url)=>{
const https = require('https');
return new Promise((resolve, reject) => {
https.get(url, (response) => {
let data = '';
//数据正在接收中...
response.on('data', (chunk) => {
data += chunk;
});
//数据接收完成
response.on('end', () => {
//console.log(JSON.parse(data));
resolve(data);//数据接收完成
});
}).on("error", (error) => {
console.log("Error: " + error.message);
reject(new Error(error.message));
});
});
};
加载结果处理
//异步调用GetJsonDataAsync(url).then(value => {
console.log("======================下面为异步加载数据=================================");
if (typeof value === "string") {
console.log('异步加载请求数据完成:', JSON.parse(value));
}
})