DEV Community

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

Posted on • Edited 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

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay