Steve Wash Steve Wash - 1 year ago 55
TypeScript Question

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) -> {
return (x);

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download