如何同步Promise对象? [英] How To Synchronise Promise Objects?

查看:106
本文介绍了如何同步Promise对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有承诺需要同步的对象。例如,第二个承诺在第一个承诺完成之前不应该起作用。如果第一个拒绝第一个必须再次执行。

I have promise objects which need to work synchronize. For example second promise shouldn't work before first one is done. If first one rejects first one has to be executed again.

我已经实现了一些例子。这个很好用。
调用getVal,等待2000ms,返回,i ++,再次调用getVal .....

I have implemented some examples.This one works well. call getVal, wait 2000ms, return, i++, again call getVal .....

 getVal() {
       return new Promise(function(resolve, reject) {
      setTimeout(function(){ resolve(19) }, 2000);
         });

     }

async promiseController(){

    for(var i =0;i<5;i++)
      {
        var _val = await this.getVal()
        console.log(_val+'prom');
      }
    }

但我需要控制一组promise对象。我想要做的是我有一个数据,我把它分成5块。在处理完第一部分之后(例如:发送到服务器)我想要处理第二部分,否则我必须再次处理第一部分。

But I need to control an array of promise objects. What I want to do is that I have a data and I divided it 5 pieces. After first part is processed(for example:sent to server) well I want to process second part otherwise I have to process first part again.

这是原型实现我已经

  getVal() {
   return new Promise(function(resolve, reject) {
  setTimeout(function(){ resolve(19) }, 2000);
     });

 }

async promiseController(){
  var proms=[]
  for(var i =0;i<5;i++)
    {
      proms.push(this.getVal())
    }

for(var i =0;i<5;i++)
  {
    var _val = await proms[i]
    console.log(_val+'prom');
  }
}

此代码中的Promises对象按顺序工作。我如何修复下面的代码,以便它作为第一个例子同步工作。

Promises objects in this code works sequentially. How can i fix the code below so that it works synchronous as first example.

推荐答案

async promiseController(){
  for(const value of array) {
    console.log((await this.getVal(value))+'prom');
  }
}

无需过度复杂化。只需在循环中调用等待,它就会等待你想要的东西。

No need to overcomplicate things. Just call await inside the loop and it'll wait for what you want.

正如另一个答案正确地说的那样 - 承诺代表而不是操作。对于操作,使用常规函数。

As the other answer rightfully said - a promise represents a value and not an operation. For operations regular functions are used.

如果要忽略失败,可以 .catch(()=> {})关于承诺。如果你想重试直到失败 - 你可以重构重试一个函数并使用它:

If you want to ignore failures you can .catch(() => {}) on the promise. If you want to retry until failures - you can refactor retry to a function and use that:

const retry = fn => (...args) => fn(...args).catch(retry(fn));

这篇关于如何同步Promise对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆