angular - 如何使用鏈式調用的 Promise?
現在在 .then 區段中,我又有另一個 promise HTTP 請求:
.then(result => { this.service().then(data => {}); });
使用鏈式承諾是一種正確的方式嗎?
答案#1
差不多!你需要在函數中回傳這個 promise,可以像這樣:
.then(result => { return this.service().then(data => {}); });
或者像這樣:
.then(result => this.service().then(data => {}));
答案#2
既然你正在使用 Typescript,你可以使用 async/await 以更可讀的方式鏈接 promises:
function firstCall(): Promise<any> { /* return a promise */ }
function service(): Promise<any>{ /* return a promise */ }
async function runPromisses() {
var result = await firstCall();
var data = await service();
// ...
}
