I am running nuts with this issue on my hobby node project. I have a function (processDataSet
) which is processing a data array (inputArray
) and returns a promise. The function uses a for loop to iterate through the input array and calls saveObjectData
function on each round. This save function handles a single data entry and also returns a promise.
It seems that if the saveObjectData
function fails, processDataSet
function catches that returned reject but its own reject
doesn't seem to get called properly inside the for loop. I believe this is a timing problem, which I don't understand. See the results of output prints below the code.
function processDataSet(inputArray, scriptConfig) {
var contentType = scriptConfig.contentType;
return new Promise(function(resolve, reject) {
if(!Array.isArray(inputArray)) {
return reject(new Error("Input data is not an array. Cannot process."));
}
if(!scriptConfig) {
return reject(new Error("Invalid scriptConfig"));
}
if(!typeof contentType === "string" && !contentType instanceof String) {
return reject(new Error("Invalid contentType for the data set. The parameter should be a string."));
}
console.log("Post processing data for the script " + scriptConfig.name + " (type: " + scriptConfig.contentType + ")");
// Iterate through the input array and handle the objects one-by-one
for (var i = 0; i < inputArray.length; i++) {
saveObjectData(inputArray[i], scriptConfig)
.then(() => {
//continue;
})
.catch(err => {
console.log("TEST PRINT " + scriptConfig.name);
return reject(new Error("Processing data object failed.", err));
});
}
console.log("Resolve " + scriptConfig.name);
return resolve();
});
}
Output prints in console:
Post processing data for the script Script1 (type: Season)
Resolve Script1
TEST PRINT Script1
It seems that the last log line including "Resolve ..." gets printed before the "TEST PRINT ..." in the error handler. Why is that and how can I make the execution to wait for the full resolution of all data entries before returning from processDataSet
?
I'm not fully sure if it's redundant in my case to make processDataSet
to return promises, but I made it as part of my troubleshooting.