我试图在迭代某些对象属性时拒绝 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)) {
reject({'message' : 'a property already exists...'});
}
//some code...
}
}
//some more code...
console.log("passed here!!!");
resolve(document);
});
}
我正在调用返回此 promise 的方法,如下所示:
updateDocumentWithNewData(doc, data).then(function(result) {
//Some code
}).catch(function(err) {
//Some code
});
解决方案是使用 bool 变量,并仅在循环完成后调用“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);
});
}
我不知道我是否错过了一些愚蠢的东西,但我认为当调用“reject”时,Promise 的拒绝应该立即返回并中断剩余的代码执行,因此第一个代码应该可以工作。我有什么遗漏的吗?
最佳答案
调用reject
不会停止promise的执行,它只会将promise的状态设置为rejected
。它不会使 promise 中断代码执行。 (但是,稍后调用 resolve
不会有任何问题,因为 Promise 的状态只能从 pending
更改为 rejected
或 完全执行
一次)
如果要中断代码执行,则需要使用returnreject(reason)
(或returnresolve(value)
)。否则,promise 将运行直到其代码结束,并且 then 与该 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);
});
}
关于javascript - 迭代对象属性时解决或拒绝 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43284340/