Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 398 Vote(s) - 3.42 Average
  • 1
  • 2
  • 3
  • 4
  • 5
'await Unexpected identifier' on Node.js 7.5

#1
I am experimenting with the `await` keyword in Node.js. I have this test script:

"use strict";
function x() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve({a:42});
},100);
});
}
await x();

But when I run it in node I get

await x();
^
SyntaxError: Unexpected identifier

whether I run it with `node` or `node --harmony-async-await` or in the Node.js 'repl' on my Mac with Node.js 7.5 or Node.js 8 (nightly build).

Oddly, the same code works in the Runkit JavaScript notebook environment:

[To see links please register here]


What am I doing wrong?
Reply

#2
Thanks to the other commenters and some other research `await` can only be used in an `async` function e.g.

async function x() {
var obj = await new Promise(function(resolve, reject) {
setTimeout(function() {
resolve({a:42});
},100);
});
return obj;
}

I could then use this function as a Promise e.g.

x().then(console.log)

or in another async function.

Confusingly, the Node.js repl doesn't allow you to do

await x();

where as the RunKit notebook environment does.
Reply

#3
As others have said, you can't call 'await' outside of an async function.
However, to get around this you can wrap the await x(); in an async function call. I.e.,

function x() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve({a:42});
},100);
});
}
//Shorter Version of x():
var x = () => new Promise((res,rej)=>setTimeout(() => res({a:42}),100));

(async ()=>{
try{
var result = await x();
console.log(result);
}catch(e){
console.log(e)
}
})();

This should work in Node 7.5 or above. Also works in chrome canary snippets area.
Reply

#4
so as suggested by others await will work inside async. So you can use the below code to avoid using then:

async function callX() {
let x_value = await x();
console.log(x_value);
}

callX();


Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through