Bat*_*ich 2 promise typescript angular
在我的应用程序中,我试图实现一种loadAll方法。
需要做的,就是调用2个http方法来加载数据。
这两种方法返回承诺。
当我尝试将它们组合成一个 promise 时,出现错误。
loadAll() {
return new Promise((resolve, reject) => {
resolve(
this.getAllItem1ToConnect(),
this.getAllItem2ToConnect();
);
}
);
}
Run Code Online (Sandbox Code Playgroud)
我意识到这是错误的,我该如何实现?
getAllItem1ToConnect 方法:
getAllItem1ToConnect() {
return this.http.get<Item1[]>(this.path + '/item').toPromise().then((res: Item1[]) => {
this.items1 = res;
});
}
Run Code Online (Sandbox Code Playgroud)
如何合并getAllItem1ToConnect,并getAllItem2ToConnect于1个承诺?
您可以使用Promise.all. 这需要一个 的数组Promises并返回一个Promise.
function func1() {
return new Promise( (res, rej) => {
setTimeout(() => res('from func1'), 1000);
});
}
function func2() {
return new Promise( (res, rej) => {
setTimeout(() => res('from func2'), 1000);
});
}
Promise.all([func1(), func2()]).then( res => console.log(res));Run Code Online (Sandbox Code Playgroud)
所以,在你的情况下,你想要:
const promise = Promise.all([
this.getAllItem1ToConnect(),
this.getAllItem2ToConnect()
]);
Run Code Online (Sandbox Code Playgroud)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
| 归档时间: |
|
| 查看次数: |
213 次 |
| 最近记录: |