Await Keyword
The await
keyword is used to wait for a promise to resolve. It can only be used within an async block.
- Execution Pause: Await makes the code wait until the promise returns a result, allowing for cleaner and more manageable asynchronous code.
Syntax
let value = await promise;
Example : This example shows the basic use of the await keyword in JavaScript.
const getData = async () => {
let y = await "Hello World";
console.log(y);
}
console.log(1);
getData();
console.log(2);
Output
1 2 Hello World
The async keyword transforms a regular JavaScript function into an asynchronous function, causing it to return a Promise.
The await keyword is used inside an async function to pause its execution and wait for a Promise to resolve before continuing.
Async and Await in JavaScript
Async and Await in JavaScript are powerful keywords used to handle asynchronous operations with promises. Async functions implicitly return promises, while Await pauses the execution until the promise is resolved. This simplifies asynchronous code and enhances readability by making it appear synchronous.