0

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();
}

2 Answers 2

4

You use await for both.

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

async is used when you declare the functions

async function functionOne() {... }
Sign up to request clarification or add additional context in comments.

2 Comments

Currently getting an error - Can not use keyword 'await' outside an async function. That might be related to my app?
@Nick You have to declare the function that this if statement is inside as async. e.g- function func() { if(someBoolen) { await func1; await func2; } }. The async keyword basiclly says this function is going to have some async operation inside, and then the await comes before that async operation and waits for it to finish before it continues the async function.
0

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)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.