简体   繁体   English

解决一个承诺中的多个承诺

[英]Resolving multiple promise within a promise

I'm writing a service method that will return a promise to get an object from an API. 我正在写一个服务方法,该方法将返回从API获取对象的承诺。 The object is returned with an array of links to get child objects from the API as well. 返回的对象带有一系列链接,也可以从API获取子对象。 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. 这里的关键是,在所有子对象都已检索并添加到父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. _.forEach更改为.map() ,然后从回调中返回嵌套的promise。
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. 然后,您可以将该数组传递给Promise.all()以获得等待它们的承诺。

Finally, you'll want to return that promise from your promise chain. 最后,您需要从承诺链中返回该承诺。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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