【问题标题】:Subsequential promises in ionic2/angular2ionic2/angular2 中的后续承诺
【发布时间】:2017-09-07 09:06:23
【问题描述】:

我知道,这是一个新手问题:

我创建了一个移动应用程序,从蓝牙串行设备读取信息源。

使用 Promise 以这种方式检索数据:

myServiceClass.getRemoteValue(valueId).then(reply: number) {
   ...
}

我需要读取来自该提要的多个参数,并且在请求新值之前我必须等待上一次调用完成。

如果我跑:

let requiredValues = [1, 2, 3, 4, ..., n];
for (let i=0; i<requiredValues.length; i++) {
   myServiceClass.getRemoteValue(valueId).then(reply: number) {
      ...
   }
}

这样请求将并行运行,但我需要它们一个接一个地运行。是否有任何解决方案可以随后以某种方式链接一系列承诺?

换句话说,我需要在前一个 promise 被解决后才运行第 n 个 promise。

非常感谢您的宝贵时间。

【问题讨论】:

    标签: javascript angular typescript ionic2 rxjs


    【解决方案1】:

    好吧,您可以使用递归方法来实现...请看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);
        });
      }
    

    【讨论】:

    • 我最终采用了一种非常相似的方法,并在最后使用 BehaviourSubject 而不是 Promise。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多