我知道,这是一个新手问题:
我创建了一个移动应用程序,从蓝牙串行设备读取信息源。
使用 Promise 以这种方式检索数据:
myServiceClass.getRemoteValue(valueId).then(reply: number) {
...
}
我需要读取来自此 feed 的多个参数,并且必须等待上一个调用完成才能请求新值。
如果我运行:
let requiredValues = [1, 2, 3, 4, ..., n];
for (let i=0; i<requiredValues.length; i++) {
myServiceClass.getRemoteValue(valueId).then(reply: number) {
...
}
}
通过这种方式,请求将并行运行,但我需要它们一个接一个地运行。是否有任何解决方案可以随后以某种方式链接一系列 promise ?
换句话说,只有在前一个 promise 得到解决后,我才需要运行第 n 个 promise 。
非常感谢您抽出时间。
最佳答案
好吧,你可以使用递归方法来实现这一点...请看一下 this plunker (运行 plunker 时,请注意这些值正在控制台中打印)
我只是使用了一些假数据,但我想这足以让您了解总体情况:
public start(): void {
this.getSeveralRemoteValues([1,2,3,4,5,6,7,8,9]);
}
private getSeveralRemoteValues(array): Promise<boolean> {
if(array && array.length) {
return this.getRemoteValueFromService(array[0]).then(() => {
array.shift(); // remove the first item of the array
this.getSeveralRemoteValues(array); // call the same method with the items left
})
} else {
this.logEnd();
}
}
private logEnd(): void {
alert('All promises are done!');
}
private getRemoteValueFromService(value: number): Promise<boolean> {
// this simulates the call to the service
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(`Promise: ${value}`);
resolve(true);
}, 1000);
});
}
关于javascript - ionic2/angular2 中的后续 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43355054/