0

If anyone found this question is a dup, please comment a link to that, or any suggestions would be appreciated.

  • The request is to fetch data bases on an array of id.

  • Function getWorkhoursById() has already been configured with axios, including the Bearer and clientId, so I want to reuse it for this purpose.

  • So, now the result will be filled up with array of ids for each fetch, but it takes some time to reach the final value. My question is how can I retrieve the final value of arrayOfIds (with all the ids in the last iteration) to perform the next task.

  • I tried the for loop method - check the last value of it, but I would like to do this in a more proper, asynchronous way.

const arrayOfIds = [];
let result = [];

const foo = (item, index, id) => {
    return new Promise((resolve, reject) => {
      setTimeout(async () => {
        const data = await getWorkhoursById(id);
        if (data.length === 0) result.push(item);
        resolve();
      }, 1000 * (index + 1)); // force async function to execute in order
    });
  };
  const bar = () => {
      return arrayOfIds.forEach(async (item, index) => {
        names(item, index, id).then(() => {
          console.log(result, "result"); // <- need the last value of result
      });
    });
  };

Henry.
  • 21
  • 6
  • `result[result.length - 1]` – zer00ne May 07 '22 at 18:52
  • 1
    To "*force async function to execute in order*", you should indeed just use a `for of` loop instead of `forEach`, and drop the `setTimeout` thing altogether: `async function bar(arrayOfIds) { const result=[]; for (const id of arrayOfIds) { const data = await getWorkhoursById(id); if (data.length==0) result.push(id); } return result; }` – Bergi May 07 '22 at 18:53
  • @Bergi, it worked. Thanks a lot . But do you know how I can 'await' for the final value, so then I can execute the next task with it? Because it takes a while for the `result` to be loaded completely. – Henry. May 07 '22 at 19:49
  • 1
    Which "*final value*", you mean the `result`? That's what the promise that `bar` returns will be fulfilled with. Just do `await bar()` where you call it – Bergi May 07 '22 at 20:26

0 Answers0