javascript - Nodejs 中的异步/等待替换

标签 javascript node.js

我正在尝试在 C# 中执行类似 async/await 的功能,但在 Node js 中 我找到了一个 example但它给了我一个错误。

这是代码

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

最佳答案

您将需要生成器 promises 以使其像async/await/Task 一样简单。

正如@Paul 所说,生成器是“ future 的功能”,因此您需要传递 --harmony--harmony-generators。此外,生成器在 V8 3.19 中受支持,仅在 Node.js 0.11.2 或更新版本中支持。

JavaScript 社区目前正在考虑多种可能的方法;其中有几个很好的概述here ,还有其他图书馆。

关于javascript - Nodejs 中的异步/等待替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20094972/

相关文章:

javascript - 页面加载时无法调用 JavaScript 函数

javascript - 使用 Gulp 输出缩小版和非缩小版

javascript - 如何从 node.js 检索数据到 Ajax?

javascript - const err = new MongooseError(message);

node.js - 了解 npm install 的输出

javascript - 如何防止用户在输入字段中输入无效字符

javascript - ArangoDB/FOXX 存储库问题

node.js - 单击页面上的按钮,直到全部被删除

javascript - 仅对字母字符进行输入验证

javascript - nodejs 需要使用 'strict use' 吗?或者 node 的严格模式的最佳实践是什么?