Todd Brannon
Todd Brannon

Reputation: 182

Proper use of async JS to ensure function calls wait for previous functions to complete (resolve?)

Trying to learn proper async/await JavaScript to run functions in sequence when an early function in the sequence would be delayed (using setTimeout to simulate). I'm not getting the expected results (still getting "first", "second", "this should run first?" - see code).

What am I missing? Do I have the wrong idea about this?

Thanks in advance!

const zeroFunction = () => {
    setTimeout(() => {
        return new Promise((resolve) => {
            console.log("This should run first?");
            resolve();
        }); 
}, 2000)}

const firstFunction = () => {
    return new Promise((resolve) => {
        console.log("first");
        resolve();
    }) 
}

const secondFunction = () => {
    return new Promise((resolve) => {
        console.log("second");
        resolve();
    })
}

async function fnAsync() {
    await zeroFunction();
    await firstFunction();
    secondFunction();
}

fnAsync();

Upvotes: 0

Views: 34

Answers (1)

morganney
morganney

Reputation: 13600

zeroFunction is currently returning undefined implicitly, not a Promise. Inverse the wrapping of the setTimeout and Promise constructor and it should work as expected.

const zeroFunction = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("This should run first?")
      resolve()
    }, 2000)
  })
}
const firstFunction = () => {
  return new Promise((resolve) => {
    console.log("first")
    resolve()
  })
}

const secondFunction = () => {
  return new Promise((resolve) => {
    console.log("second")
    resolve()
  })
}

async function fnAsync() {
  await zeroFunction()
  await firstFunction()
  secondFunction()
}

fnAsync()

Upvotes: 2

Related Questions