I have an array of publishers and each publisher have motionID, this ID is used to get data from API Like
'http://ift.tt/1DaGbqf'+publisher.motion+'/events/?page='
publisher.motion is motionID. Every publisher of the motion have multiple pages of event.
'http://ift.tt/1DaGbqf'+publisher.motion+'/events/?page=1'
'http://ift.tt/1DaGbqf'+publisher.motion+'/events/?page=2'
.
.
'http://ift.tt/1DaGbqf'+publisher.motion+'/events/?page=n'
I want to collected all the events from all pages of motion and save to that publisher.motionEvent array.And I also want to call another function when all data is collected for all publishers. And Publisher are push into allProduct array
My Code:
getEventsOfPublishes(objectList,'M')
}).then(function(allPublisherWithMotionEvents){
console.log(allPublisherWithMotionEvents)
})
here objectList is all publisher which have motionID as there Property.
function getEventsOfPublishes(objectList,key){
if(objectList.length){
if(key == 'M'){
var promises = objectList.map(getEventsOfMotion);
return Q.all(promises);
}
}else{
return {msg:"No Objects"};
}
}
using q.map for calling function for each publisher.
function getEventsOfMotion(publisher){
if(publisher.motion !== undefined){
//console.log('motion')
url = 'http://ift.tt/1DaGbqf'+publisher.motion+'/events/?page=';
publisher.motionEvent = []
getAllDataOfEvents(1,url,'M',publisher).then(function(test){
allProducts.push(test)
//console.log(test)
})
}else{
console.log('yes')
}
}
calling function 'getAllDataOfEvents' for those publisher which have motion Id, as there property.
function getAllDataOfEvents(currentPage,url,key,publisher){
var deferred = Q.defer();
var result
httprequest(url+currentPage,
function(err, res, body) {
var events = JSON.parse(body);
var next;
var tempDeviceObject = {}
// console.log(events.objects)
saveProducts(events.objects,key,publisher)
if(events.links.next != null){
currentPage++
getAllDataOfEvents(currentPage,url,key,publisher).then(function(){
deferred.resolve(publisher)
});
}else{
result = deferred.resolve(publisher);
}
})
return deferred.promise;
}
function saveProducts(objects,key,publisher){
if(key === 'M'){
if(objects){
//console.log(objects.length+'---------'+publisher.motion)
objects.forEach(function (event) {
var tempEventobject = {}
tempEventobject.date = event.dateEvent;
tempEventobject.durationSeconds = event.data.durationSeconds
tempEventobject.numberMovements = event.data.numberMovements
tempEventobject.avgIntensity = event.data.avgIntensity
tempEventobject.eventID = publisher.motion
publisher.motionEvent.push(tempEventobject)
})
//console.log(publisher);
}
}else{
// console.log(publisher)
}
}
In the above code all events are collected in publisher.motionEvent, but allPublisherWithMotionEvents is array of undefined i.e the function is not waiting for that to be collected. I have used Q module. Thanks for Your help.
Aucun commentaire:
Enregistrer un commentaire