Thursday, 27 April 2017

javascript - node.js and asynchronous programming palindrome


The below code is not asynchronous, why and how do I make it?




function compute(callback){
for(var i =0; i < 1000 ; i++){}
callback(i);

}


I'm going to assume your code is trying to say, "I need to do something 1000 times then use my callback when everything is complete".



Even your for loop won't work here, because imagine this:



function compute(callback){
for(var i =0; i < 1000 ; i++){
DatabaseModel.save( function (err, result) {

// ^^^^^^ or whatever, Some async function here.
console.log("I am called when the record is saved!!");
});
}
callback(i);
}


In this case your for loop will execute the save calls, not wait around for them to be completed. So, in your example, you may get output like (depending on timing)




I am called when the record is saved
hii
I am called when the record is saved
...


For your compute method to only call the callback when everything is truely complete - all 1000 records have been saved in the database - I would look into the async Node package, which can do this easily for you, and provide patterns for many async problems you'll face in Node.



So, you could rewrite your compute function to be like:




function compute(callback){
var count = 0
async.whilst(
function() { return count < 1000 },
function(callback_for_async_module) {
DatabaseModel.save( function (err, result) {
console.log("I am called when the record is saved!!");
callback_for_async_module();
count++;
});

},
function(err) {
// this method is called when callback_for_async_module has
// been called 1000 times

callback(count);
);
console.log("Out of compute method!");
}



Note that your compute function's callback parameter will get called sometime after console.log("Out of compute method"). This function is now asynchronous: the rest of the application does not wait around for compute to complete.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...