mslavs
mslavs

Reputation: 33

returning array after promises within loop

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;
    });

  }

Upvotes: 1

Views: 65

Answers (1)

Patrick Roberts
Patrick Roberts

Reputation: 51766

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.

Upvotes: 2

Related Questions