I tried to reject a promise while iterating through some object properties, but the execution continues even after reject method was called ("passed here!!!" was logged in the console, even after the rejection).
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);
});
}
I'm calling the method that returns this promise like this:
updateDocumentWithNewData(doc, data).then(function(result) {
//Some code
}).catch(function(err) {
//Some code
});
The solution was to use a boolean variable, and call the "reject" method only after the loop finishes:
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);
});
}
I don't know if i'm missing something stupid, but I think that the rejection of the Promise should return imediatelly when "reject" is called and break the remaining code execution, so the first code should work. Is there something that I'm missing?