Promises & Await & Async :
Prommises
Async & Await
Promises:
promise is a good way to handle asynchronous operations.
It is used to find out if the asynchronous operation is successfully completed or not.
promise may have one of three states.
1.Pending
2.Fulfilled
3.Rejected
A promise starts in a pending state.
That means the process is not complete.
If the operation is successful, the process ends in a fulfilled state.
And, if an error occurs, the process ends in a rejected state.
For example, when you request data from the server by using a promise, it will be in a pending state.
When the data arrives successfully, it will be in a fulfilled state.
If an error occurs, then it will be in a rejected state.
// Example function that returns a promise
function fetchData() {
return new Promise((resolve, reject) => {
// Simulating an asynchronous operation (e.g., fetching data from an API)
setTimeout(() => {
const data1 = { name: 'John', age: 30 };
// Resolve the promise with the fetched data
reject(data1);
resolve(data1);
// Reject the promise if an error occurs
// reject(new Error('Failed to fetch data.'));
}, 2000);
});
}
// Consuming the promise
fetchData()
.then((data) => {
// Promise is resolved, handle the fetched data
console.log('Fetched data:', data);
})
.catch((error) => {
// Promise is rejected, handle the error
console.log('Error:Mesg');
})
.finally(() => {
// This block is executed regardless of the promise result (success or failure)
console.log('Promise operation completed.');
});
Async and Await
:
We use the async keyword with a function to represent that the function is an asynchronous function.
The async function returns a promise.
The syntax of async function is:
async function name(parameter1, parameter2, ...paramaterN) {
// statements
}
Here,
name - name of the function
parameters - parameters that are passed to the function
JavaScript await Keyword :
The await keyword is used inside the async function to wait for the asynchronous operation.
Syntax :
The syntax to use await is:
let result = await promise;
The use of await pauses the async function until the promise returns a result (resolve or reject) value.
For example,:
// a promise
let promise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('Promise resolved')}, 4000);
});
// async function
async function asyncFunc() {
// wait until the promise resolves
let result = await promise;
console.log(result);
console.log('hello');
}
// calling the async function
asyncFunc();
Output :
Promise resolved
hello