繁体   English   中英

节点 JS 从 url 获取 JSON 在其余代码之后执行

[英]Node JS Fetching JSON from url is executing AFTER the rest of the code

我想从节点 JS 代码中的 URL 获取 JSON。 代码运行良好,但由于执行的异步性质,执行顺序混乱。

var http = require("https");

var number = 37302;

// these functions need to execute is sequence.    

console.log('Before API Call');

var response = fetchJson(number);
console.log(response);

console.log('After API Call');  



function fetchJson(number)
{        

    var url = 'https://example.com/api/getactionitems/' + number;

    http.get(url, function(res){
        var body = ''; 

        res.on('data', function(chunk){
            body += chunk; 
            console.log('JSON Retrieved.');               
        });

        res.on('end', function(){

            console.log('Parsing JSON');

            var APIResponse = JSON.parse(body);

            var Name = APIResponse.EmpName;
            var outstring = APIResponse.ActionItem;                
            return ('Hi ' + Name + ', Your action Items are: '+ outstring);            
        });
    })
    .on('error', function(e){
      return ("Got an error while fetching data.");
    });

}

这段代码执行时,输出字符串的顺序如下:

Before API Call
undefined
After API Call
JSON Retrieved.
Parsing JSON

如何更正执行顺序,使顺序如下所示:

Before API Call
JSON Retrieved.
Parsing JSON
<Outpt from the JSON parsing>
After API Call
var http = require("https");

var number = 37302;

// these functions need to execute is sequence.    


console.log('Before API Call');

fetchJson(number).then(function(res){

console.log(res);

console.log('After API Call');
}).catch(function(e){console.log('err',e)});



function fetchJson(number)
{        
return new Promise(function(resolve,reject){
    var url = 'https://example.com/api/getactionitems/' + number;

    http.get(url, function(res){
        var body = ''; 

        res.on('data', function(chunk){
            body += chunk; 
            console.log('JSON Retrieved.');               
        });

        res.on('end', function(){

            console.log('Parsing JSON');

            var APIResponse = JSON.parse(body);

            var Name = APIResponse.EmpName;
            var outstring = APIResponse.ActionItem;                
            resolve('Hi ' + Name + ', Your action Items are: '+ outstring);            
        });
    })
    .on('error', function(e){
      reject("Got an error while fetching data.");
    });
});

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM