JavaScript: Async functions (async/await)
JavaScript: Async functions (async/await)
Here is the MDN definition for async and await:
async:
“An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.”
await:
“An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value. Remember, the await keyword is only valid inside async functions.”
Confused………..
Lets put this defination in this way
A function defined as async is a function that can perform asynchronous actions but still look synchronous. The way it's done is using the await keyword to defer the function while it waits for a Promise to resolve or reject.
async and await build on top of promises and generators to express asynchronous actions inline. This makes asynchronous or callback code much easier to maintain.
Syntax:
async function name([param[, param[, ...param]]]) {
statements
}
Let see its implementation:
function resolveAfter2Seconds() { return new Promise(resolve => { setTimeout(() => { resolve('resolved'); }, 2000); }); } async function asyncCall() { console.log('calling'); const result = await resolveAfter2Seconds(); console.log(result); // expected output: "resolved" } asyncCall();
OUTPUT:> "calling"> "resolved"
An async function always returns a Promise itself, so you can use it in other asynchronous functions.
SomeThing you should know about Await:
Await and operator precedence:
await getData().getDataSize();
}
That's very useful content share your blog well go on thanks a lot
ReplyDeleteThanks for your comment. We are looking forward to improve more.
Deletenice
ReplyDelete