-2

I have different functions running in different if statements. I want to go back to the previous else if after the one of the other has been run. I tried to write a promise but that ran too soon.

My code:

(async() => {
  let dev = await getAllTables({
    query: tables(dev_id)
  });
  let prod = await getAllTables({
    query: tables(prod_org)
  });

  result.data.table_fields.forEach((d) => {
    if (d.type != "connected_field") {
      axiosfunc1();
    } else if (d.label in dev) {
      axiosfunc2();
    } else if (d.label in prod) {
      axiosfunc3()
      .then((res) => res)
      .then((x) => {
         axiosfunc2();
       });
    } else {
      console.log(`${d.label} DOES NOT EXIST}`);
    }
  });
})();

axiosfunc2() is running at the same time as axiosfunc3() rather than having axiosfunc3() run first and then axiosfunc2().

How do I fix that?

nb_nb_nb
  • 1,243
  • 11
  • 36
  • 2
    I doubt `d.label in prod` is executing both at the same. It is more likely that `table_fields` contains labels that are both in `dev` and `prod` so different iterations are kicking off different branches of the `if` statement concurrently – sinanspd May 02 '23 at 02:42
  • Does this answer your question? [Resolve promises one after another (i.e. in sequence)?](https://stackoverflow.com/questions/24586110/resolve-promises-one-after-another-i-e-in-sequence) – jsejcksn May 02 '23 at 03:06

1 Answers1

-1

You can use a for...of loop and await all the Promises so that they are executed sequentially.

for (const d of result.data.table_fields) {
    if (d.type != "connected_field") {
      await axiosfunc1();
    } else if (d.label in dev) {
      await axiosfunc2();
    } else if (d.label in prod) {
      const res = await axiosfunc3();
      await axiosfunc2();
    } else {
      console.log(`${d.label} DOES NOT EXIST}`);
    }
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80