8

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)
Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159
asv
  • 3,332
  • 7
  • 24
  • 47
  • Are you sure it's supported without any flags? From what I can see [here](http://kangax.github.io/compat-table/es2016plus/), it looks like you need to spawn your node with either `--harmony` or `--es_staging` flag. – Tomasz Lenarcik Dec 27 '16 at 14:55

1 Answers1

9

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

EDIT

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.

Chris Montgomery
  • 2,344
  • 2
  • 19
  • 30