在NodeJs 8. *如何在http.get上应用Async / Await?
下面的代码从指定的url中asynchronous获取结果,并且在接收到数据后,使用nodejs版本8中的asynchronous/等待(*)(不带callback函数),我想从getData方法中返回parsed
variables。
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; };
任何帮助是非常appriciated。
首先让我说,我build议使用npm包request
处理http获取,说。
1.)使用Promise (等待在后台执行此操作)
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.)或callback函数你可以通过callback(parsed)
函数callback(parsed)
或callback(error_msg)
函数callback(error_msg)
来callback(parsed)
getData
( getData(v, r, callback)
callback(error_msg)
。
然后用法是:
getData(v, r, result=>console.log(result))
或者更容易阅读也许:
function callback(res) { console.log(res) } getData(v, r, callback)