asynchronous/等待在Nodejs中取代

我想做一个像C#中的asynchronous/等待的function,但在节点js我find了一个例子,但它给了我一个错误。

这里是代码

function* gotNews(response){ console.log("in gotNews"); str=''; response.on('data', function (chunk) { str += chunk; }); response.on('end', function () { str = JSON.parse(str); console.log(str); fetchCategories(); }); return str; } function fetchNews(sourceURL){ console.log("in fetch news"); sourceURL = url.parse(sourceURL); console.log(sourceURL); var options = { host: sourceURL.host, port: 134, path: sourceURL.path, method: 'GET', }; var req = http.request(options,yield gotNews);//start request and recive response in gotSources req.end(); } 

我使用* yield操作,但给我一个错误

 ErrorC:\Users\Alaa\Desktop\Fluid_layout_with_jQuery_Masonry\1\app.js:198 var elnewselygat = yield gotNews(); ^^^^^^^ SyntaxError: Unexpected identifier at Module._compile (module.js:439:25) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:901:3 

您需要生成器承诺,使其像async / await / Task一样简单。

正如@保罗所说,发电机是一个“未来function”,所以你需要通过--harmony--harmony-generators 。 另外,在V8 3.19中只支持Node.js 0.11.2或更新版本。

JavaScript社区正在考虑一些可能的方法; 这里有好几个关于它们的概述,还有其他一些库。

检查: https : //github.com/luciotato/waitfor-es6

它用发电机做你想做的。 (不需要承诺)

函数* —-> c#asynchronous

(fn …)—> c#等待

您可以使用babel --stage 1 --optional runtime使用async/await