JavaScript Async Await is a modern way of writing asynchronous code in JavaScript. It allows you to write code that is easier to read, understand, and debug. Async Await is part of the ES6 (ECMAScript 6) specification and is a way to write asynchronous code without using callbacks or promises.
async function doSomething() {
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('done!');
}, 1000);
});
const result = await promise;
console.log(result);
}
doSomething();
In the example above, the async function is declared with the async keyword and the await keyword is used to pause the execution of the function until the promise is resolved. Once the promise is resolved, the function will continue to execute.
Async functions can also be used to handle tasks such as making network requests. In the example below, we use an async function to make a network request and then await the response.
async function getData() {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await response.json();
console.log(data);
}
getData();
In the example above, the async function is declared with the async keyword and the await keyword is used to pause the execution of the function until the network request is completed. Once the request is completed, the response is logged to the console.
To learn more about async, visit Async.
The await
keyword is used to wait for a Promise. It can only be used inside an async
function. The await
keyword will pause the execution of the async
function and wait for the Promise to resolve prior to moving on.
When a Promise is awaited, the function will return the resolved value of the Promise. If the Promise is rejected, the await
expression will throw an error.
In the example below, we have an async
function that uses the await
keyword to wait for a Promise to resolve before logging the result to the console.
async function example() {
const result = await Promise.resolve('Hello World!');
console.log(result);
}
example();
In this example, we have an async
function that uses the await
keyword to wait for a Promise to resolve before returning the result.
async function example() {
const result = await Promise.resolve('Hello World!');
return result;
}
example().then(result => console.log(result));
It is important to note that the await
keyword can only be used inside an async
function. If it is used outside of an async
function, it will throw an error.
To learn more about await, visit Await.