Aysnc function in javascript
In JavaScript, the async function is used to define a function that returns a promise. The async keyword is placed before the function keyword when declaring a function. An async function can contain an await expression, which pauses the execution of the function until the promise is resolved, and then resumes the execution and returns the resolved value.
Here's a basic example:
async function exampleAsyncFunction() {
console.log("Before await");
const result = await somePromise(); // Pauses execution until somePromise is resolved
console.log("After await, result:", result);
return result;
}
function somePromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise resolved!");
}, 1000);
});
}
// Using the async function
exampleAsyncFunction().then((result) => {
console.log("Async function result:", result);
});
In this example, exampleAsyncFunction
is an asynchronous function that uses the await
keyword to wait for the resolution of the somePromise
function before moving on. The somePromise
function returns a promise that resolves after a timeout of 1000 milliseconds.
Keep in mind that the async
keyword can only be used with function declarations, function expressions, and arrow functions. Additionally, an async
function always returns a promise, and the value it returns will be wrapped in a resolved promise or the function itself can explicitly return a promise using Promise.resolve()
or Promise.reject()
.
Async/await is especially useful for working with asynchronous code in a more synchronous-like manner, making it easier to read and reason about asynchronous code.