[英]async/await replace in Nodejs
I am trying to do a function like async/await in C# but in node js I have found an example but It gives me an error. 我试图在C#中执行像async / await这样的函数,但在节点js中我找到了一个例子,但它给了我一个错误。
here is the code 这是代码
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();
}
I am using the * yield operation but gives me an error 我正在使用* 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
You'll need generators and promises to make it as easy as async
/ await
/ Task
. 您需要生成器和承诺,使其像async
/ await
/ Task
一样简单。
As @Paul stated, generators are a "future feature" so you need to pass --harmony
or --harmony-generators
. 正如@Paul所说,发电机是一种“未来特征”,所以你需要通过--harmony
或--harmony-generators
。 Also, generators are supported in V8 3.19, which is only in Node.js 0.11.2 or newer. 此外,V8 3.19支持生成器,它仅在Node.js 0.11.2或更高版本中。
The JavaScript community is currently considering a number of possible approaches; JavaScript社区目前正在考虑许多可能的方法; there's a good overview of several of them here , and there are other libraries out there as well. 有几个人一个很好的概述, 这里 ,还有其他的库出有作为。
check: https://github.com/luciotato/waitfor-es6 检查: https : //github.com/luciotato/waitfor-es6
It does what you want, with generators. 它使用发电机做你想要的。 (no promises required) (不需要承诺)
function* ----> c# async function * ----> c#async
yield wait.for(fn...) ---> c# await yield wait.for(fn ...)---> c#等待
你可以使用async/await
和babel --stage 1 --optional runtime
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.