Reputation: 28493
I need to loop over a set of objects and check for a value inside a callback function. My problem is, if the value is not found, I need to throw a single error, so this needs to be outside of the callback and loop.
Right now I have this:
for (i = 0; i < response._conflicts.length; i += 1){
del_rev = response._conflicts[i];
// retrieve a document
that.addJob(
"get",
someID,
options,
// callback
function (response) {
if (condition 1) {
if (condition 2){
console.log("gotcha");
// run a function
f.removeDocument(someID+x);
return;
}
}
},
function (err) {
that.error({ "status": 123 });
}
);
} // end of loop
// now if the loop turns out no results, I need to throw this error
that.error({ "status": 404 });
return;
My problem is, the second 404
error triggers before my callback check can detect if the conditions are met or not, so I'm always ending up with a 404
and second function triggering, once the conditions are met and my f.removeDocument(someID+x)
triggers.
I have tried removing f.removeDocument(someID+x)
from the callback and loop and only setting a variable to true/false and then throwing my error or calling my function. However, same result = the variable is false and throws the error before it's set to true in the callback.
I guess I need to put my 404
error inside the loop and inside the callback, but I don't know how I can ensure it only fires ONCE when the loop is done and conditions have not been met.
Question:
How can I throw an error ONCE inside a callback function, which is triggered in a loop?
Upvotes: 1
Views: 217
Reputation: 6414
This looks like an asynchronicity problem. To handle the callback as a kind of join operation you will need to wait for the last callback. A pattern like this might help:
var join = (function(n, fn) {
return function() {
if(--n === 0) {
fn();
}
}
}) (response._conflicts.length, function() {
// Check the conditions
});
The join function will count down the required number of times and then allow you to perform the rest of the checking after the last call has completed. You will need to trigger join()
in your request callback.
Upvotes: 2