我想從API的多個頁面檢索產品收集數據
像
https://example.com/v2/nodes/?resource__type=device&page=1
https://example.com/v2/nodes/?resource__type=device&page=2
.
.
每個頁面有鏈接,這樣接下來的API: var devices = JSON.parse(body); devices.links.next
我想檢索所有頁面中的所有數據。我也想調用所有數據時調用另一個函數。
我的代碼:
getAllNodeData(1,"https://example/v2/nodes/?resource__type=device&page=", 'A').then(function(objectList){
console.log('--------')
console.log(allProducts.length)
})
function getAllNodeData(currentPage,url,key){
var deferred = Q.defer();
var result
httprequest(url+currentPage,
function(err, res, body) {
var devices = JSON.parse(body);
var next;
var tempDeviceObject = {}
//console.log(devices)
saveProducts(devices.objects,key)
if(devices.links.next != null){
currentPage++
return getAllNodeData(currentPage,url,key)
}else{
console.log('I am here')
result = deferred.resolve(allProducts);
}
// if(devices.totalObjects == allProducts.length){
//}
})
return deferred.promise;
}
function saveProducts(objects,key){
if(key === 'A'){
objects.forEach(function (device) {
var tempDeviceObject = {}
tempDeviceObject.id = device.uid
tempDeviceObject.name = device.label
tempDeviceObject.type = device.resource.slug
device.publishes.forEach(function(pub){
if((pub.label=== 'Motion') && (pub.type.toLowerCase() === 'motion')){
var currentPage = 1;
var key = 'M';
var url = "https://crossoft:[email protected]/v2/feeds/"+pub.uid+"/events/?page=";
tempDeviceObject.motion =pub.uid
// return getEventsOfPublishes(pub.uid,url,key,currentPage)
}else if((pub.label=== 'Battery') && (pub.type.toLowerCase() === 'battery')){
tempDeviceObject.battery =pub.uid
}else if((pub.label=== 'Temperature') && (pub.type.toLowerCase() === 'temperature')){
tempDeviceObject.temperature =pub.uid
}
})
allProducts.push(tempDeviceObject)
})
return allProducts
//console.log(allProducts.length)
}
}
在上面做了我要當devices.links.next返回allProducts = null是真正的即未來= NULL。目前。然後功能不起作用。我正在使用q模塊。
感謝您的幫助。
https://stackoverflow.com/questions/23803743/what-is-the-deferred-antipattern-and-how-do-i-avoid-it – Bergi 2015-02-23 12:42:41
'allProducts'初始化在哪裏? – Bergi 2015-02-23 12:44:12