node.js - 异步等待与 nodejs 7

标签 node.js async-await

我已经安装了 nodejs 7.3.0 并且我有这段代码:

let getContent = function (url) {
    // return new pending promise
    return new Promise((resolve, reject) => {
        // select http or https module, depending on reqested url
        const lib = url.startsWith('https') ? require('https') : require('http');
        const request = lib.get(url, (response) => {
            // handle http errors
            if (response.statusCode < 200 || response.statusCode > 299) {
                reject(new Error('Failed to load page, status code: ' + response.statusCode));
            }
            // temporary data holder
            const body = [];
            // on every content chunk, push it to the data array
            response.on('data', (chunk) => body.push(chunk));
            // we are done, resolve promise with those joined chunks
            response.on('end', () => resolve(body.join('')));
        });
        // handle connection errors of the request
        request.on('error', (err) => reject(err))
    })
};

let get = async function (url) {
    var content = await getContent(url);
    return content;
}

var html = get('https://developer.mozilla.org/it/');

在调试中我收到这个:

let get = async function (url) {
                ^^^^^^^^
    SyntaxError: Unexpected token function
        at Object.exports.runInThisContext (vm.js:78:16)
        at Module._compile (module.js:543:28)
        at Object.Module._extensions..js (module.js:580:10)
        at Module.load (module.js:488:32)
        at tryModuleLoad (module.js:447:12)
        at Function.Module._load (module.js:439:3)

最佳答案

Node 7.3.0 does not support async/await without a feature flag .像这样的生成 Node 应该可以解决问题:

node --harmony-async-await app.js

编辑

Node 现在正式支持 async/await by default in version 7.6.0 ,来自将 Chromium 的 JavaScript 引擎 V8 更新为 version 5.5 .

关于node.js - 异步等待与 nodejs 7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41347260/

相关文章:

javascript - 为什么第一个程序有效而第二个程序无效?

javascript - Node.Js 中有海象运算符吗?

javascript - NodeJS |循环 JSON 给出 undefined

javascript - 如何在 Node.js 中使用 async/await 编写依赖项

c# - 异步方法的延迟进度报告

javascript - 无法使用nodejs的pdf2json处理多个pdf文件

php - 验证 socket.io/nodejs 的用户

c# - 如何使 Dispose 等待所有异步方法?

c# - 等待 Task.Result 会如何影响嵌套的异步/等待方法?

javascript - 如何访问异步获取函数的值?