Another approach to return a value from an asynchronous function, is to pass in aan object that will store the result from the asynchronous function.
Here is an example of the same:
var async = require("async");
// This wires up result back to the caller
var result = {};
var asyncTasks = [];
asyncTasks.push(function(_callback){
// some asynchronous operation
$.ajax({
url: '...',
success: function(response) {
result.response = response;
_callback();
}
});
});
async.parallel(asyncTasks, function(){
// result is available after performing asynchronous operation
console.log(result)
console.log('Done');
});
I am using the result
object to store the value during the asynchronous operation. This allows the result be available even after the asyncasynchronous job.
I use this approach alota lot. I would be interstedinterested to know how well this approach works where wiring the result back through consecutive modules is involved.
Hope this helps.