Make a blocking call to a function in Node.js required in this case?

后端 未结 3 1178
春和景丽
春和景丽 2021-01-22 13:24

I am starting to learn node.js. I am stuck with a problem here. I am calling a weather service which returns a JSON(url below).

http://api.wunderground.com/api/Your_ke

3条回答
  •  故里飘歌
    2021-01-22 13:40

    you can take a callback in your module function to return the result.

    module.exports = function (url, onsuccess) {
        ...
    
        res.on('end', function() {
            fbResponse = JSON.parse(body);
            if(onsuccess){
                onsuccess(null, fbResponse);
            }
    

    Then in your caller code:

    relay(url, function(err, result){
        console.log(result);
    });
    

    Another option is to use httpsync module which provides synchronous apis for the same functionality that 'http' module provides. But in node js programming, you should always avoid synchronous calls.

提交回复
热议问题