Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async await with nodejs 7

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)
like image 807
asv Avatar asked Dec 27 '16 14:12

asv


People also ask

Can I use async await in NodeJS?

Async functions are available natively in Node and are denoted by the async keyword in their declaration. They always return a promise, even if you don't explicitly write them to do so. Also, the await keyword is only available inside async functions at the moment – it cannot be used in the global scope.

How do you write async await in node JS?

With Node v8, the async/await feature was officially rolled out by the Node to deal with Promises and function chaining. The functions need not to be chained one after another, simply await the function that returns the Promise. But the function async needs to be declared before awaiting a function returning a Promise.

How do I use await in node JS?

The await operator is used to wait for a Promise . It can only be used inside an async function within regular JavaScript code; however it can be used on its own with JavaScript modules.

Is await blocking NodeJS?

async/await does not block the whole interpreter. node. js still runs all Javascript as single threaded and even though some code is waiting on an async/await , other events can still run their event handlers (so node. js is not blocked).

What is async/await in Node JS?

With Node v8, the async/await feature was officially rolled out by the Node to deal with Promises and function chaining. The functions need not to be chained one after another, simply await the function that returns the Promise.

What is the async/await syntax in ES7?

One of the most exciting features coming to JavaScript (and therefore Node.js) is the async / await syntax being introduced in ES7. Although it's basically just syntactic sugar on top of Promises, these two keywords alone should make writing asynchronous code in Node much more bearable.

What does the async keyword DO in JavaScript?

The async keyword is used when you're defining a function that contains asynchronous code. This is an indicator that a Promise is returned from the function and should therefore be treated as asynchronous. Here is a simple example of its usage (notice the change in the function definition):

How does await function work in JavaScript?

The code above basically asks the javascript engine running the code to wait for the request.get () function to complete before moving on to the next line to execute it. The request.get () function returns a Promise for which user will await .


1 Answers

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.

like image 78
Chris Montgomery Avatar answered Oct 19 '22 08:10

Chris Montgomery