1

I am trying to aggregate the responses after running a loop and having promises being called each time. However, the function does not wait for all the promises to be done and returns undefined.

getAllPluginImpls(): DesktopPluginDefinitionImpl[] {
    let pluginArray: DesktopPluginDefinitionImpl[] = [];
    let promises = [];
    Array.from(this.pluginMap.keys()).forEach(id =>
      promises.push(this.pluginManager.findPluginDefinition(id).then(
        def => {
          console.log("id");
          console.log(id);
          console.log("def");
          console.log(def);
          let pluginImpl = def as DesktopPluginDefinitionImpl;
          pluginArray.push(pluginImpl);
        }
      )
    )
    );
    Promise.all(promises).then(s => {
      console.log("end reached :(");
      console.log(pluginArray);
      return pluginArray;
    });

  }
6
  • You need to return your promise. Commented Jul 16, 2018 at 15:57
  • 1
    Use .map(), not .forEach() Commented Jul 16, 2018 at 15:57
  • 1
    Instead of pushing to an array, return the value from your promise and Promise.all() will give you what you want. Commented Jul 16, 2018 at 15:57
  • yes but i want to ultimately return the array Commented Jul 16, 2018 at 16:00
  • 1
    You need to return a promise of the array. Commented Jul 16, 2018 at 16:02

1 Answer 1

2

First of all, you should be returning Promise<DesktopPluginDefinitionImpl[]>, and secondly as pointed out in comments, the complexity of your method would be greatly simplified by avoiding usage of .forEach() to .push() entries into a scoped array.

getAllPluginImpls(): Promise<DesktopPluginDefinitionImpl[]> {
  const pluginArray: Promise<DesktopPluginDefinitionImpl>[] = Array.from(
    this.pluginMap.keys(),
    id => this.pluginManager.findPluginDefinition(id)
  );

  return Promise.all(pluginArray);
}

And to clarify, the Promise<DesktopPluginDefinitionImpl>[] is not a typo. Promise.all() converts an array of promises into a promise of an array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.