【发布时间】:2020-06-03 13:19:00
【问题描述】:
我正在尝试使用 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
我做错了什么?
我也尝试过使用回调,但效果总是一样的。
【问题讨论】:
-
为什么两者都给
this.price = price;赋值???这是错字吗? -
你想只使用 Promise 还是我们可以使用 observables 来做到这一点?
-
您无需等待异步函数完成即可立即解决承诺。 Promise 包装器不会使它们同步
-
如果不是
3,1,2,你期待什么序列? -
1.事实上,我添加到表格中,我希望示例尽可能简单。 2. 我希望 then() 段在末尾@bjdose Prefer Promise。
标签: angular typescript