【问题标题】:Resolving or Rejecting a Promise while iterating through object properties [duplicate]在遍历对象属性时解决或拒绝 Promise [重复]
【发布时间】:2017-04-08 02:08:04
【问题描述】:

我在迭代某些对象属性时尝试拒绝一个承诺,但即使在调用拒绝方法后执行仍在继续(“通过这里!!!”即使在拒绝后也已登录控制台)。

function updateDocumentWithNewData(document, newData) {
 return new Promise(function(resolve, reject) {
    //some code...
    for (let key in newData) {
      if (newData.hasOwnProperty(key)) {
        //verifying if the document already has the property
        if (document.hasOwnProperty(key)) {
          reject({'message' : 'a property already exists...'});
        }
        //some code...
      }
    }
        
    //some more code...
    console.log("passed here!!!");
    resolve(document);
  }); 
}

我正在调用返回此承诺的方法,如下所示:

updateDocumentWithNewData(doc, data).then(function(result) {
  //Some code  
}).catch(function(err) {
  //Some code
});

解决方案是使用布尔变量,只有在循环结束后才调用“reject”方法:

function updateDocumentWithNewData(document, newData) {
  return new Promise(function(resolve, reject) {
    //some code...
    let invalidUpdate = false;
    for (let key in newData) {
      if (newData.hasOwnProperty(key)) {
        //verifying if the document already has the property
        if (document.hasOwnProperty(key)) {
          invalidUpdate = true;
          break;
        }
        //some code...
      }
    }
    if (invalidUpdate) {
      reject({'message' : 'a property already exists...'});
    }
    
    //some more code...
    console.log("passed here!!!");
    resolve(document);
  }); 
}

我不知道我是否遗漏了一些愚蠢的东西,但我认为 Promise 的拒绝应该在调用“reject”时立即返回并中断剩余的代码执行,所以第一个代码应该可以工作。有什么我遗漏的吗?

【问题讨论】:

    标签: javascript promise es6-promise


    【解决方案1】:

    调用reject 不会阻止promise 的执行,它只会将promise 的状态设置为rejected。它不会使承诺中断代码执行。 (但是,稍后调用resolve 不会有任何问题,因为Promise 的状态只能从pending 更改为rejectedfulfilled 一次)

    如果要中断代码执行,需要使用return reject(reason)(或return resolve(value))。否则,promise 将一直运行到其代码结束,并且然后任何与该 promise 关联的.then 回调都将被调用。这是预期的行为。立即停止 Promise 执行的另一种方法是抛出一个错误,这将导致 Promise 因该错误而拒绝。

    所以让你的原始代码工作的方法是:

    function updateDocumentWithNewData(document, newData) {
     return new Promise(function(resolve, reject) {
        //some code...
        for (let key in newData) {
          if (newData.hasOwnProperty(key)) {
            //verifying if the document already has the property
            if (document.hasOwnProperty(key)) {
              return reject({'message' : 'a property already exists...'});
            }
            //some code...
          }
        }
    
        //some more code...
        console.log("passed here!!!");
        resolve(document);
      }); 
    }
    

    【讨论】:

    • 谢谢,佩德罗。完美的解释——现在我在 Promises 的测试中看到的其他一些奇怪的行为也很有意义! :)
    猜你喜欢
    • 2014-09-28
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    • 2020-09-17
    相关资源
    最近更新 更多