简体   繁体   中英

Resolving multiple promise within a promise

I'm writing a service method that will return a promise to get an object from an API. The object is returned with an array of links to get child objects from the API as well. The key here is that I don't want the outer promise to resolve until all of the child objects have been retrieved and added to the parent MyType. The following is CLOSE to what I want, but I don't know how to get the promise to wait for the child objects to be resolved before returning.

private getRegistrationDetailsPromise(url: string): Promise<MyType> {    
  return new Promise<MyType>((resolve) => {
     return this.dataService.GetMyType(url)
       .then((myType: MyType) => {                    
          _.forEach(myType.childReferences, function(childUrl) {
            let child = this.dataService.GetChild(childUrl).then((child) -> {
                myType.children.push(child);
            };
        };                  
        return (x);
    });
});

Change _.forEach to .map() , and return the nested promise from the callback.
That will give you an array of promises.

You can then pass that array to Promise.all() to get a promise that waits for all of them.

Finally, you'll want to return that promise from your promise chain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM