Home / Shopify / What is an async function?

An async function is a function declared with the async keyword, and the await keyword is permitted within it. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains. 

async/await builds on top of promises: an async function always returns a promise. await “unwraps” a promise and either results in the value the promise was resolved with, or throws an error if the promise was rejected.

Why do we need to use async functions?

We need to use them because they allow you to write promise-based code as if it were synchronous, but without blocking the main thread. They make your asynchronous code less “clever” and more readable. 

Example:

async function firstAsyncFunction() { 
  try { 
    const fulfilledValue = await promise; 
  } 
  catch (rejectedValue) { 
    // … 
  } 
} 

How to return a value from an async function?

If you use the async keyword before a function definition, you can then use await within the function. When you await a promise, the function is paused in a non-blocking way until the promise settles. If the promise is fulfilled, you get the value back. If the promise rejects, the rejected value is thrown. 

Example:

async function callAsyncFunction(name){ 
return new Promise((resolve, reject) => { 
    resolve(`My name is ${name}`) 
  }) 
} 
 
async function getName(name){ 
const result = await callAsyncFunction(name); 
  return result; 
} 
 
(async () => { 
console.log(await getName('Blerona Idrizi')) 
})() 
 
 
The result wil be: My name is Blerona Idrizi 

Arrange a free consultation now!