Await function in javscript
The await keyword is used in JavaScript within async functions to wait for a Promise to settle (either resolve or reject) before continuing with the execution of the code. It can only be used inside functions that are declared with the async keyword.
When the await keyword is used, it causes the async function to pause and wait for the Promise to be resolved. During this pause, the event loop is not blocked, and other code can continue to execute. Once the Promise is resolved, the async function resumes its execution and returns the resolved value.
Here's a basic example:
function delay(time) {
return new Promise(resolve => {
setTimeout(() => {
resolve(`Resolved after ${time} milliseconds`);
}, time);
});
}
async function exampleAsyncFunction() {
console.log("Start");
// Using await to pause until the promise is resolved
const result = await delay(2000);
console.log(result);
console.log("End");
}
exampleAsyncFunction();
In this example, the delay function returns a Promise that resolves after a specified delay. The exampleAsyncFunction uses await delay(2000) to pause its execution for 2000 milliseconds until the promise is resolved.
When you run this code, it will output:
In this example, the delay function returns a Promise that resolves after a specified delay. The exampleAsyncFunction uses await delay(2000) to pause its execution for 2000 milliseconds until the promise is resolved.
When you run this code, it will output:
The await
keyword can also be used with other Promise-based asynchronous operations, such as fetching data from a server, reading a file, or any other operation that returns a Promise. It provides a more concise and readable syntax for handling asynchronous code compared to using callbacks or plain Promises.