0

Currently I am stuck at coding which is the output should be in proper sequence. I have loop, if-statement and Axios call in it. The code is something like these.

var job = [[obj1.Clean], [obj2.Wash], [obj3.Clean]];
for (i = 0; i < job.length; i++) {
  if (job.task == "Clean") {
    console.log("Clean");
    clean();
  } else if (job.task == "Wash") {
    console.log("Wash");
    wash();
  }
}

async function clean() {
  //await Axios 1 here
}

async function wash() {
  //await Axios 2 here
}

What makes wonder is the output appears as following:

Clean
Wash
Clean
[output axios 1]
[output axios 2]
[output axios 1]

Thus what should I do in order to obtain such sequence?

Clean
[output axios 1]
Wash
[output axios 2]   
Clean
[output axios 1]

p/s: the best documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Mohamad Aiman
  • 43
  • 1
  • 11

1 Answers1

1

Disclaimer: I'm a newbie, read with caution.

Use for...of loop instead to work with an async function. forEach and for statements will fire all without waiting:

async function doJob () {    
for (j of job) {
    if (j.task == "Clean") {
        console.log("Clean");
        await clean();
      } else if (j.task == "Wash") {
        console.log("Wash");
        await wash();
    }
}

I refer to another post. Btw, in case you have more steps, maybe a switch statement would suit your purpose better than an if-else statement because you're using string instead of boolean according to this article. This one is also a good read on for statements.