在NodeJs 8. *如何在http.get上应用Async / Await?

时间:2017-07-27 04:39:12

标签: node.js asynchronous async-await

以下代码从指定的url异步获取结果,并且我希望在收到数据之后从getData方法返回parsed变量,在nodejs版本8中使用async / await。* (没有回调函数)。

function getData(v, r) {
    var path = 'http://some.url.com';
    var parsed = "";
    http.get({
        path: path
    }, function(res) {
        var body = '';
        res.on('data', function(chunk) {
            body += chunk;
        });
        res.on('end', function() {
            parsed = JSON.parse(body);
            // now I would like to return parsed from this function without making use of callback functions, and make use of async/await;
        });
    }).on('error', function(e) {
        console.log("Got error: " + e.message);
    });
    return parsed;
};

任何帮助都非常适合。

1 个答案:

答案 0 :(得分:1)

首先请允许我说我建议使用npm包request来处理http获取,这就是说。

1。)使用承诺(等待在后台执行此操作)

function getData(v, r) {
  var path = 'http://some.url.com';
  var parsed = '';
  return new Promise((resolve, reject) => {
    http.get({
      path: path
    }, function(res) {
      var body = '';
      res.on('data', function(chunk) {
        body += chunk;
      });
      res.on('end', function() {
        parsed = JSON.parse(body);
        resolve(parsed);
      });
    }).on('error', function(e) {
      reject(e.message);
    });
  });
};

然后使用

getData(v, r)
  .then(success => console.log(success))
  .catch(error => console.log(error))

2。)或回调您可以将回调作为参数传递给getData(即getData(v, r, callback)),然后在函数体内通过{{ 1}}或callback(parsed)

然后用法是:

callback(error_msg)

或者更容易阅读:

getData(v, r, result=>console.log(result))