使用nodejs 7异步等待 [英] async await with nodejs 7

查看:104
本文介绍了使用nodejs 7异步等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经安装了nodejs 7.3.0,并且具有以下代码:

I've installed nodejs 7.3.0 and I have this code:

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/');

在调试中,我收到以下消息:

In debug I receive this:

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)

推荐答案

节点7.3.0不支持异步/等待功能标记.这样的生成节点应该可以解决问题:

Node 7.3.0 does not support async/await without a feature flag. Spawning node like this should do the trick:

node --harmony-async-await app.js

编辑

Node现在正式支持默认情况下在版本7.6中异步/等待.0 ,来自将Chromium的JavaScript引擎V8更新为

Node now officially supports async/await by default in version 7.6.0, which comes from updating V8, Chromium’s JavaScript engine, to version 5.5.

这篇关于使用nodejs 7异步等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆