Function declaration:
async function myFunc() {
// Function body here
};
myFunc();
We can also use async function expressions.
const myFunc = async () => {
// Function body here
};
myFunc();
async functions always return a promise. This means we can use traditional promise syntax, like .then() and .catch with our async functions.
Remember that an async function returns a promise with a resolved value equal to the return value of that function. The function:
function nativePromise(){
return new Promise((resolve, reject) => {
resolve('yay!');
})
}
// Could be written:
async function asyncPromise(){
return 'yay!';
}
The await operator
The async function doesn’t work alone, it needs help from the keyword await inside the function.
await keyword returns the resolved value of a promise. await halts, or pauses, the execution of our async function until a given promise is resolved.
async function asyncFuncExample(){
let resolvedValue = await myPromise();
console.log(resolvedValue);
}
asyncFuncExample(); // Prints: I am resolved now!
Within our async function, asyncFuncExample(), we use “await” to halt our execution until myPromise() is resolved and assign its resolved value to the variable resolvedValue. Then we log resolvedValue to the console.
Remember that the await operator returns the resolved value of a promise.
try ...catch:
Within the try block, we can use promise and promise’s resolve value; within the catch block, we can use reject’s reasons or show error messages.
async function usingTryCatch() {
try {
let resolveValue = await asyncFunction('thing that will fail');
let secondValue = await secondAsyncFunction(resolveValue);
} catch (err) {
// Catches any errors in the try block
console.log(err);
}
}
usingTryCatch();
Handling Independent Promises:
We can assign a promise into a variable and then we can print the promise’s resolve value.
async function waiting() {
const firstValue = await firstAsyncThing();
const secondValue = await secondAsyncThing();
console.log(firstValue, secondValue);
}
Or we can assign the promise's resolve into a variable then we can print the promise’s resolve value.
async function concurrent() {
const firstPromise = firstAsyncThing();
const secondPromise = secondAsyncThing();
console.log(await firstPromise, await secondPromise);
}
Await Promise.all()
async function asyncPromAll() {
const resultArray = await Promise.all([asyncTask1(), asyncTask2(), asyncTask3(), asyncTask4()]);
for (let i = 0; i<resultArray.length; i++){
console.log(resultArray[i]);
}
}
Promise.all() will receive an argument that will be the array of multiple promises.
The resolved value of Promise.all() will be the resolved value of promises.
If any of the promises in the array rejects, the promise returned from Promise.all() will reject for that reason.
Post a Comment