I thought async/await was supported in node 7.4, however this example does not work:
const Promise = require('bluebird');
async function main(){
await Promise.delay(1000)
}
main();
Results in:
async function main(){
^^^^^^^^
SyntaxError: Unexpected token function
How can I use async/await with node 7.4?
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.
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.
The await expression causes async function execution to pause until a promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled promise.
async and await Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
Yes async-await is supported in Node.js v7 but its locked behind the harmony
flag. Features which are not yet production ready are behind this flag.
To use async-await in Node.js v7 simply run Node service with this flag -
node --harmony-async-await app.js
The official release of async-await is slated for Node.js v8 which will be launched in April.
You can follow this pull request to check its status. Basically the correct functioning of async-await is dependent on the integration of V8 engine v5.5 into Node.js. Currently Node.js uses V8 v5.4 which is solved by this pull request.
Update 1 - It seems V8 v5.5 might be coming to Node.js v7. Follow this pull request for more details.
Update 2 - Good news guys! Node.js version 7.6.0 now officially supports async
functions without using the --harmony
flag as V8 engine 5.5 has been successfully ported.
Now you only need to use the --harmony
flag if your Node.js version is between 7.0 to 7.5.0 (inclusive). For complete changelog refer here.
Node.js 7.6.0 released several hours ago and they included v8 5.5. Now you can use async/await without flag.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With