0% found this document useful (0 votes)
11 views

Asyncjs

Async/await provides a way to write asynchronous code that looks synchronous by allowing functions declared with the async keyword to pause execution until promises resolve using the await keyword. This allows code execution to pause at the line marked with await until the promise settles, then resume with the result so the code in the example shows an alert of "done!" after one second without blocking other tasks from running during the delay.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Asyncjs

Async/await provides a way to write asynchronous code that looks synchronous by allowing functions declared with the async keyword to pause execution until promises resolve using the await keyword. This allows code execution to pause at the line marked with await until the promise settles, then resume with the result so the code in the example shows an alert of "done!" after one second without blocking other tasks from running during the delay.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

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.

You might also like