Summary: In this tutorial, you will learn to write asynchronous function in Javascript using Promises and async/await.
To write an asynchronous function in JavaScript, you can use either Promises or async/await.
Asynchronous Function using Promises
Here is an example of an asynchronous function using Promises:
const myAsyncFunc = () => {
return new Promise((resolve, reject) => {
// Do something asynchronous
setTimeout(() => {
// If the async operation is successful, call resolve
resolve('Async operation complete');
}, 1000);
});
}
myAsyncFunc().then((result) => {
console.log(result); // 'Async operation complete'
});
Here, the myAsyncFunc
function is an asynchronous function that returns a Promise. A Promise is an object that represents the result of an asynchronous operation.
The myAsyncFunc
function uses the setTimeout
function to execute some code after a specified amount of time (in this case, one second).
Inside the setTimeout
callback, the resolve
function is called with the string ‘Async operation complete’ as an argument. This causes the Promise to resolve to the value ‘Async operation complete’.
The myAsyncFunc
function is called by the code myAsyncFunc().then((result) => { console.log(result); });
.
The then
method is called on the returned Promise, and it takes a callback function as an argument. This callback function is executed when the Promise resolves, and it receives the resolved value as an argument (in this case, ‘Async operation complete’).
Asynchronous Function using async/await
Here is an example of an asynchronous function using async/await:
const myAsyncFunc = () => {
return new Promise((resolve, reject) => {
// Do something asynchronous
setTimeout(() => {
// If the async operation is successful, call resolve
resolve('Async operation complete');
}, 1000);
});
}
async function myAsyncFunction() {
const result = await myAsyncFunc();
console.log(result); // 'Async operation complete'
}
myAsyncFunction();
In this example, the myAsyncFunc
function is the same as in the first example. The myAsyncFunction
function is an asynchronous function that calls myAsyncFunc
and waits for the Promise to resolve using the await
keyword.
The await
keyword can only be used inside an async
function, and it causes the code to pause until the Promise is resolved.
In this case, the await
keyword is used to wait for the myAsyncFunc
Promise to resolve, and then the resolved value is stored in the result
variable. Finally, the result
variable is logged to the console.