Nick
Nick

Reputation: 2549

async/await concurrent function calls in javascript (Chain functions)

I think I'm probably misunderstanding how to use async/await, but I'm struggling to find a solution that doesn't dive into promises.

I have an if statement that contains two functions. I need functionTwo to run only after functionOne has completed. adding async and await before them doesn't seem to work, but I don't think I'm a million miles away.

Any help would be great! Thank you!

if (someBoolean) {
  functionOne();
  functionTwo();
}

if (someBoolean) {
  async functionOne();
  await functionTwo();
}

Upvotes: 0

Views: 77

Answers (2)

Gerard
Gerard

Reputation: 801

async/await uses Promises! So I think that's not the best way to go if you want to avoid Promises. Your best bet might be to include a callback in your first function.

function one(callback) {
  /* do your stuff here */
  if (typeof callback === 'function) {
    callback()
  }
}

function two() {/* do the second set of things here */}

if (someBoolean) {
  one(two)
}

Upvotes: 0

Jamiec
Jamiec

Reputation: 136124

You use await for both.

if (someBoolean) {
  await functionOne();
  await functionTwo();
}

async is used when you declare the functions

async function functionOne() {... }

Upvotes: 4

Related Questions