I have an Object that I want to loop through and run against a series of IF statements. Each IF statement makes an HTTP Request. The results of the HTTP Request gets pushed into an Array. I need to execute a function after looping through the object.
How do I execute a function ONLY after the Looping and IF statements are finished?
Code:
function myFunction(Object, res) {
var resultArray;
for (var obj in Object) {
if (something is true) {
//do something
resultArray.push(result)
}
}
//After the for loop is confirmed finished, do callback
res(resultArray)
}
I think you can still do this asynchronously. First you will need to get all the properties out of your object:
//Gather up all the properties;
var properties = [];
for(var property in object) if(object.hasOwnProperty(property) {
properties.push(property);
}
//Array of results
var resultsArray = [];
//This is a named, self-invoked function that basically behaves like a loop. The
//loop counter is the argument "i", which is initially set to 0. The first if
//is basically the loop-termination condition. If i is greater than the
//total number of properties, we know that we're done.
//
//The success handler of the ajax call is where the loop is advanced. This is also
//where you can put your if condition to check if something is true, so that you
//can insert the data into the results array. At the end of the success handler,
//you basically call the named self-invoked function, but this time with the
//loop counter incremented.
(function iterateOverProperties(i) {
if(i < properties.length) {
var property = properties[i];
var value = object[property];
//assuming jQuery just for demonstration
jQuery.ajax({
url: "someurl",
data: value;
success: function(data) {
if(something is true) {
resultArray.push(data);
}
iterateOverProperties(++i);
}
});
} else {
res(resultArray);
}
})(0);
I think the module traverse-chain will just match this scenario.
var Chain = require('traverse-chain');
function myFunction(Object, res) {
var resultArray;
// Create a chain that is to be traversed.
var chain = new Chain();
for (var obj in Object) chain.add(function() {
if (something is true) {
//do something
resultArray.push(result)
// next
chain.next();
} else {
// process next anyway.
chain.next();
}
});
chain.traverse(function() {
//Do the callback when the traversing is done
res(resultArray);
})
}