我正在尝试使用 Promise 在 Angular 中编写同步函数调用,但它仍然得到与预期不同的结果。 我有 2 个使用从 API 下载数据的服务的函数:
getData1(shortcut: string): void {
this.apiServ.getPrice(shortcut).subscribe(
(price: CurrentPrice) => {
this.price = price;
console.log(1);
},
error => this.error = error
);
}
getData2(shortcut: string): void {
this.apiServ.getPrice(shortcut).subscribe(
(price: CurrentPrice) => {
this.price = price;
console.log(2);
},
error => this.error = error
);
}
我正在尝试在响应完成后进行下一个函数调用。所以:
data(shortcuts) {
this.getData1(shortcuts[0]);
this.getData2(shortcuts[1]);
}
ngOnInit() {
const myPromise = new Promise((resolve) => {
this.data(this.shortcuts);
resolve(3)
});
myPromise.then((value) => {console.log(value)});
}
但是我的浏览器打印了这个调用顺序:
3
1
2
我做错了什么?
我也尝试过使用回调,但效果总是一样。
最佳答案
如果你想使用 Promise,你可以使用async/await,但你也可以使用 rxjs 来做到这一点。
可观察流量
我创建了两个函数来模拟您的问题,一个称为 getDataAsObservable ,它代表您的 getData 方法,另一个称为 getDataAsPromise ,它代表您的 promise ,然后我使用 concat,它是 rxjs 中的一种可观察创建方法,它顺序发出所有值从给定的 Observable 开始,然后移动到下一个。
我将first$、second$和third$异步函数传递给concat和subscribe以打印结果。
promise 流程
否则,如果使用async/await,则只需等待响应即可。
import { Observable, concat } from 'rxjs';
import { delay } from 'rxjs/operators';
async ngOnInit() {
// first execute promise flow and wait for the response
await this.executePromiseFlow();
// after promise flow we can execute observable flow
this.executeObservableFlow();
}
executePromiseFlow = async () => {
// I use toPromise method to convert observable to a promise
const first = await this.getDataAsObservable(1).toPromise();
console.info('[Promise] output', first);
const second = await this.getDataAsObservable(2).toPromise();
console.info('[Promise] output', second);
const third = await this.getDataAsPromise(3);
console.info('[Promise] output', third);
}
executeObservableFlow = () => {
const second$ = this.getDataAsObservable(2);
const first$ = this.getDataAsObservable(1);
const third$ = this.getDataAsPromise(3);
concat(first$, second$, third$)
.subscribe((output) => console.info('[Observable] output', output))
}
getDataAsObservable = (value: number) => {
return new Observable((observer) => {
observer.next(value);
observer.complete();
}).pipe(
delay(value * 2000), // simulate HTTP request time
);
}
getDataAsPromise = (value: number) => {
return Promise.resolve(value);
}
您可以阅读有关异步/等待的更多信息 here和 rxjs here .
您可以查看此 here on Stackblitz 的简单复制品
关于angular - Angular 9 中的 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62165241/