Reputation: 8413
I have the following function in my node.js app which loops through an array and performs a certain function on it:
var splitStatements = ['1','2','3']; // this is simplified
splitStatements.forEach(function(statement) {
// `statement` is written into the database
// the response is obtained and modified as `response`
console.log(response);
});
How do I ensure that no matter how complex the function inside the forEach
function is, each element of the array would be processed one by one, so that the result output is something like
1 modified
2 modified
3 modified
In reality I sometimes get something like
1 modified
3 modified
2 modified
Depending on how complex each element of splitStatements
array is.
I understand that the above happens because the code execution is asynchronous, so what is the best practice way to ensure that while it is executed asynchronously each next procedure ensures that the previous one has been performed already in order to be started?
Upvotes: 0
Views: 1394
Reputation: 8413
I found a solution: I simply timestamp every statement
that enters into the database adding a few milliseconds to each (that equals this statement's position inside the array). So if it's 1st, I add 1, if it's 2nd I add 2, etc.
Then when I extract those statements from the database I simply sort them by this timestamp (which was already the case).
Upvotes: 0
Reputation: 943650
If the order you insert the data in really matters, then you need to wait for each query to finish before sending the next one.
Don't use a for loop.
Write a function which sets the next item in the array to the database. Call that function once directly, and then again inside the callback that indicates the asynchronous database call is complete.
Include a test so you stop when you run out of items in the array!
If you don't need to preserve the contents of the array, you can use arr.unshift()
to get the next item. If you don't get a result, you have reached the end.
If you need to preserve the array, then use a variable (traditionally i
) to keep track of which array index you are at. Increment it by one each time.
function insert_into_database() {
var item = arr.unshift();
if (item) {
add_to_database(item).then(insert_into_database);
}
}
Upvotes: 2
Reputation: 5698
Problem in your not structured array from database, issue not in forEach
You need to send query to database with sort or order options
Upvotes: 0