【问题标题】:How to stop Promise.all loop when it rejects拒绝时如何停止 Promise.all 循环
【发布时间】:2019-04-25 01:39:48
【问题描述】:

如果一个 promise 拒绝它,我很难尝试停止 promise.all 中的循环。这就是我的做法。这有什么问题吗?

 Promise.all(myArray.map((obj) => {
      this.someFunction(obj);
 }))

这是我调用的函数..

someFunction(){
 return new Promise(function (resolve, reject) {
    ....
     reject()
 })}

【问题讨论】:

  • 映射返回一个数组并“立即”创建,Promise.all 将在数组中的所有 Promise 均已解析时解析,如果有则拒绝。你到底想达到什么目的?

标签: react-native promise


【解决方案1】:

我已经更新了我的代码,它已经过测试,它可以在我的机器上使用我提供的模拟数据运行。我不确定你的其余代码的结构是如何的,但它是这样的:哦,你不能打破地图,但我们将使用一个简单的 for 循环,因为我们可以打破它:

function someFunction(){
 return new Promise(function (resolve, reject) {
      // I will be rejeccting a boolean
      // If you are resolving something, resolve it as true
     reject(false)
 })}


async function shouldStopLoop(){

  // the boolean will come here
  // if it is false, the catch block will return
  // if it is true, the try block will return

  let stopLoop = null;
  let result = null;

  try {
     result = await someFunction();
     return result
  } catch(error) {
    stopLoop = error;
    return stopLoop;
  }
}

function mayReturnPromiseAll() {

  let myArray = ['stuf to loop over...']
  let arraytoGoInPrimiseAll = [];


  // Array.prototype.map cannot be stopped
  // Thats why we will use a for loop and we will push the data we need
  // into another array 
  for (var i = 0; i < myArray.length; i++) {
    if (!this.someFunction(obj)) {
        break;
    } else {
      // push things in arraytoGoInPrimiseAll
    }
  }

  if(arraytoGoInPrimiseAll.length > 0){
    return Promise.all(arraytoGoInPrimiseAll)
  } else {
    // do something else
  }

};

【讨论】:

  • 仍然可以正常工作。一旦承诺遭到拒绝,我希望停止循环。有办法吗?
【解决方案2】:

试试这个:

const arrayOfFunctions = myArray.map(obj => this.someFunction(obj))
Promise.all(arrayOfFunctions).then(values => {
 console.log(values);
}).catch(error => {
  console.log(error)
});

【讨论】:

    猜你喜欢
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    相关资源
    最近更新 更多