使用Node.js 7的async/await技术

8
我已经安装了Node.js 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)

你确定它不需要任何标志就能支持吗?从我所看到的这里来看,似乎你需要使用 --harmony--es_staging 标志来启动你的节点。 - Tomasz Lenarcik
1个回答

9

非常感谢。我不知道有关标志选项的信息。 - asv
1
@asv 警告:不建议在生产环境中使用! - Bamieh
谢谢大家。对于生产环境,也许我们必须等待 Node 8.0.0。 - asv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接