Async/await
There’s a special syntax to work with promises in a more comfortable fashion,
called “async/await”. It’s surprisingly easy to understand and use.
The function execution “pauses” at the line (*) and resumes when the promise
settles, with result becoming its result. So the code above shows “done!” in one
second.
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // wait until the promise resolves (*)
alert(result); // "done!"
}
f();
Let’s emphasize: await literally suspends the function execution until the promise
settles, and then resumes it with the promise result. That doesn’t cost any CPU
resources, because the JavaScript engine
can do other jobs in the meantime: execute other scripts, handle events, etc.