JavaScript — Async and Await functions
when I came to know about async and await in recent times. I want to learn what the thing is, so here is what I have learned so far.
Async
the word async denotes the asynchronous operation which is in javascript
Await
the word await denotes that wait for something or hold something until the process is done
JavaScript default behavior
Basically while executing the script, the javascript won’t wait for asynchronous operations. it will mainly concentrate on the synchronous operations. Here is where the Promise functions are used.
Promise
It represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
In another word even though javascript prefers synchronous operations. the Promise holds the value on execution and resulting when it’s done. It helps the asynchronous functions to hold the result until the process is done.
Eg: fetch()
When we need to hold the process, that’s where Async and Await comes.
Note: Await can be only used within asynchronous functions
A simple example of async and await operation.
async function iAmAsync() {let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("I'm done!"), 2000)
});let result = await promise; // wait till the promise resolves (*)alert(result); // "I'm done!"
}();
If you like this article. click the applause button! 👏 Follow me on Github, Twitter, Facebook.