Reputation: 165
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function f1() {
var x = await resolveAfter2Seconds(10);
console.log(x);
}
f1();
let x = 3;
Why do we see the following scenario?
Why JS not waiting on await and steps forward? May you give me an advice?
Upvotes: 11
Views: 15407
Reputation: 61904
f1
is asynchronous (the await only occurs within that asynchronous context). Therefore, f1()
is executed, and because it's async, the let x = 3;
line executes immediately without waiting.
If you also await
the call to f1()
, it should do what you're expecting. However in order to use await
, you must wrap that code inside another async
function, and then execute that function.
Demo (no await):
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function f1() {
var x = await resolveAfter2Seconds(10);
console.log(x);
}
f1();
let x = 3;
console.log(x);
Working version (with extra await):
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function f1() {
var x = await resolveAfter2Seconds(10);
console.log(x);
}
async function f2() {
await f1();
let x = 3;
console.log(x);
};
f2();
You can't use await
outside an async
context...so at the end of the chain something has to be async. The bottom line is, anything you want to be waiting until after the f1()
executes must be either
f2()
function after the await
, or.then()
callback attached to the promise.Upvotes: 12
Reputation: 826
More simpler
(async function() {
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function f1() {
var x = await resolveAfter2Seconds(10);
console.log(x);
}
await f1();
let x = 3;
console.log(x);
})();
Upvotes: 4