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

后端 未结 3 1174
春和景丽
春和景丽 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:48

    You need to pass in a callback instead:

    var http = require('http');
    
    module.exports = function(url, cb) {
        http.get(url, function(res) {
            var body = '';
    
            res.on('data', function(chunk) {
                body += chunk;
            });
    
            res.on('end', function() {
                var resp, err;
                try {
                  resp = JSON.parse(body);
                } catch (ex) {
                  err = ex;
                }
                cb(err, resp);
            });
    
        }).on('error', function(e) {
              console.log("Got error: ", e);
              cb(e);
        });
    };
    

    Then use it like:

    var relay = require('./getInfo');
    var url = 'http://api.wunderground.com/api/Your_key/conditions/q/CA/San_Francisco.json';
    var response;
    relay(url, function(err, resp) {
      if (err) throw err; // TODO: handle better
      console.dir(resp);
    });
    

提交回复
热议问题