Home > Blockchain >  Do these two async functions run in parallel?
Do these two async functions run in parallel?

Time:07-21

Let's say we have two async functions like so:

const getUrl = async () => ...logic

const getName = async () => ...logic

and then I want to define an object which the values of the keys are these functions such as:

const defineObject = async() => {

   const obj = {
      url: await getUrl()
      name: await getName()
   }
}

Is this going to behave as generally JS does where it waits for the first async function to run getUrl() and then runs the second async function getName(), or, does it run them in parallel.

CodePudding user response:

No, they won't run in parallel. Each use of await turns into a getXXX().then(), with the code after it put into the .then() callback function.

If you want to do that, you can use Promise.all().

const [url, name] = await Promise.all([getUrl(), getName()]);
const obj = {url, name};
  • Related