DEV Community

Cover image for JavaScript Async Functions
 Bishnu Prasad Chowdhury
Bishnu Prasad Chowdhury

Posted on • Updated on

JavaScript Async Functions

JAVASCRIPT ASYNC FUNCTIONS

An async function is an object of AsyncFunction declared using the keyword async, also it can be used along with await keyword.

The await can only be used in a function that is declared aysnc. async/await functions can use try/catch block hence error handling for asynchronous code becomes easier. await makes the asynchronous function wait for either being resolved or rejected.

Async functions are used to improve the readability of code which are written to handle APIs that return promises.

function imageAPI(){
    return Promise.resolve(5);
}

on using async on the above function it becomes:

async function imageAPI(){
    return 5;
}
Enter fullscreen mode Exit fullscreen mode

Async/await can be used like below for hooks served from API -

async function imageAPI(){
   let data = await get('../somedoc.json');
   let objects = await data.json();
   await new Promise((resolve, reject) => setTimeout(resolve, 1000));

}
Enter fullscreen mode Exit fullscreen mode

The rejection is handled with a try/catch block where if the promise results in an error the catch block should handle the code.

async function imageAPI(){
   let data = await get('../somedoc.json');
   let objects = await data.json();

}
imageAPI().catch(console.log(e));
Enter fullscreen mode Exit fullscreen mode

await can be used with Promise.all where more than one promise can be handled.

async function imageAPI(){
    let data = await Promise.all([
    get('../1.json),
    get('../2.json)
 ]);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)