异步等待与nodejs 7

时间:2016-12-27 14:46:39

标签: node.js async-await

我已经安装了nodejs 7.3.0,我有这个代码:

$this->set('_jsonOptions', JSON_UNESCAPED_UNICODE);
$this->set('_serialize', ['zones']);

在调试中,我收到了这个:

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

1 个答案:

答案 0 :(得分:9)

Node 7.3.0 does not support async/await without a feature flag。像这样的产卵节点应该可以解决这个问题:

node --harmony-async-await app.js

修改

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