问题
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?
回答1:
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.
回答2:
Node.js 7.6.0 released several hours ago and they included v8 5.5. Now you can use async/await without flag.
回答3:
You will need harmony flag for this to work.
Try again with node --harmony-async-await myscript.js
回答4:
Node version 7.6 now supports async/await out of the box. If you haven’t tried it yet, you should adopt it immediately and never look back.
const makeRequest = () =>
getJSON()
.then(data => {
console.log(data)
return "done"
})
makeRequest()
And using async/await:
const makeRequest = async () => {
console.log(await getJSON())
return "done"
}
makeRequest()
回答5:
I had the same issue, what I did is installed asyncawait using below command
npm install asyncawait
afterwards i declared await and async using below command
const async = require('asyncawait/async');
const await = require('asyncawait/await');
then used these where it was required but my commands were within async(my-code) & await(my-code)
.
And it worked perfectly for me.
来源:https://stackoverflow.com/questions/41756622/using-async-await-in-node-7-4