Собирайте данные из разных API и отправляйте их вместе в ответ

0 Muddassir Khanani [2015-02-23 15:26:00]

Я хочу получить продукт с нескольких страниц 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)
    }
}

В приведенном выше примере я хочу вернуть allProducts, когда device.links.next! = Null является true, т.е. next = null. В настоящее время функция не работает. Я использую модуль q.

Спасибо за вашу помощь.

javascript node.js q


2 ответа


1 Решение Zeeshan Hassan Memon [2015-02-23 15:49:00]

Требуется только одно изменение.

return getAllNodeData(currentPage,url,key)

замените выше строку в getAllNodes следующим образом, и все будет хорошо

getAllNodeData(currentPage,url,key).then(function(){
 deferred.resolve(allProducts)
});

Счастливая помощь!


0 Bergi [2015-02-23 17:11:00]

Ваша проблема - это линия

return getAllNodeData(currentPage,url,key)

в узле. Вы не можете return оттуда, возвращаясь только в then.

Кроме того, вы используете отложенный антипаттерн. Вместо этого обещайте только функцию httprequest, а затем используйте только обещания. В вашем случае функция должна выглядеть так:

var promiseRequest = Q.nfbind(httprequest);

function getAllNodeData(currentPage, url, key) {
    return getNodeData(currentPage, []);

    function getNodeData(currentPage, allProducts) {
        return promiseRequest(url+currentPage).then(function(res, body) {
            var devices = JSON.parse(body);
            var tempDeviceObject = {}
            allProducts = saveProducts(devices.objects, allProducts)
            if (devices.links.next != null) {
                return getNodeData(currentPage+1, allProducts)
            } else {
                console.log('I am here')
                return allProducts;
            }
        });
    }
    function saveProducts(objects, allProducts) {
        if (key === 'A') {
            objects.forEach(function (device) {
                var tempDeviceObject = {
                    id: device.uid,
                    name: device.label,
                    type: device.resource.slug
                };
                device.publishes.forEach(function(pub) {
                    if ((pub.label==='Motion') && (pub.type.toLowerCase()==='motion')) {
                        tempDeviceObject.motion = pub.uid;
                    } 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;
    }
}