Asynchronous Javascript Issue
I'm trying to make a function details() that looks up the details of certain events (getdetails) based on the available events. In the example below, details are asked for the even
Solution 1:
One way is to use the async library, in particular the async.each
or async.eachSeries
function. (You could use async.map
, but in your case you are actually not mapping, but modifying the underlying array items directly.)
In particular, your code would look like this:
async.each(res.Data, function(val,callback){
getdetails(val.ID).then(function(data){
tmp = JSON.parse(data);
Object.keys(tmp.Data[0]).map(function(v,j){
val[v] = tmp.Data[0][v];
});
callback(null); // Asynchronous code has finished without error
}, function(error){ //error callbackcallback(error); // Asynchronous code has finished with error
});
}, function(error) {
// All asynchronous calls have finishedif(error)
console.log("Error", error);
elseconsole.log("Success", res);
});
async.each
will run many iterations at the same time, while async.eachSeries
will run only one iteration at the same time.
Solution 2:
Well you already use promise - see then
in your code and if it's angular then then
itself return deferred promise so you can do:
res.Data.map(function (val, i) {
getdetails(val.ID).then(function (data) {
tmp = JSON.parse(data);
Object.keys(tmp.Data[0]).map(function (v, j) {
val[v] = tmp.Data[0][v];
});
}, function (error) { //error callbackconsole.log(error)
}).then(function () {
console.log(JSON.stringify(res));
})
});
EDIT: inject service $q
into your controller or service
promises = [];
res.Data.map(function (val) {
promises.push(getdetails(val.ID).then(function (data) {
tmp = JSON.parse(data);
Object.keys(tmp.Data[0]).map(function (v, j) {
val[v] = tmp.Data[0][v];
});
}, function (error) { //error callbackconsole.log(error)
}));
});
$q.all(promises).then(function () {
console.log(JSON.stringify(res));
});
now when all the getdetails
are resolved you can console.log or do whatever you want with the data
Post a Comment for "Asynchronous Javascript Issue"