Home > Mobile >  How to stack promises dynamically?
How to stack promises dynamically?

Time:02-11

I have a nested object subprojects with a property of type array: userEstimates holding object(s) Estimate.

I am looking to iterate through userEstimates and push a fetch/promise to an array without calling it.

main (inside async function)

await subproject.getUserEstimates(true);
let stack = [];

subproject.userEstimates.forEach(ue =>
    stack.push(ue.fetchAvailableRates)
);

console.log(stack);  // 3) [ƒ, ƒ, ƒ]

await Promise.all(stack);

fillForm(subproject);

however, attributes on subproject are not defined when calling fillForm

function definition for fetchAvailableRates:

fetchAvailableRates = () => {
  this.availableRates = fetch(...)
  .then((resp) => {
    if (resp.ok) return resp.json();
    else throw new Error("Something went wrong");
  })
  .then((r) => {
    ...

    return {
      Rate.get(), // returns class
      ...
    };
  })
  .catch((e) => {
    console.error(e);
  });
};

EDIT: Changed my wording frrom queue to stack as i'm trying to run all requests at once, and I don't care about order

CodePudding user response:

Your definition for fetchAvailableRates uses this, but when you refer to an object's function without calling it (like stack.push(ue.fetchAvailableRates)), it loses the reference to this and simply becomes a function.

To refer to a function that calls ue.fetchAvailableRates on the ue instance at the time, you should call either () => ue.fetchAvailableRates() or ue.fetchAvailableRates.bind(ue).

That's not the only change you'd need to make―Promise.all() doesn't accept functions, only promises, so the right call is probably to make ue.fetchAvailableRates() return the Promise and add that to the stack.

  • Related