Just going through this tutorial, and it baffles me to understand why await
only works in async
function.
From the tutorial:
As said, await only works inside async function.
From my understanding, async
wraps the function return object into a Promise, so the caller can use .then()
async function f() {
return 1;
}
f().then(alert); // 1
And await
just waits for the promise to settle within the async
function.
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // wait till the promise resolves (*)
alert(result); // "done!"
}
f();
It seems to me their usage are not related, could someone please explain?
async
andawait
are both meta keywords that allow asynchronous code to be written in a way that looks synchronous. Anasync
function tells the compiler ahead of time that the function will be returning aPromise
and will not have a value resolved right away. To useawait
and not block the threadasync
must be used.is equivalent to