2016-07-25 5 views
0

Ich rufe eine API von Drittanbietern an und ich habe Probleme, alle Rückgaben zu sammeln und sie als 1 Array in meiner API zurückzugeben. Ich kann sehen, dass ich erfolgreich telefoniere und sie zurückkommen. Aufgrund asynch wird das endgültige Array zurückgegeben, bevor es ausgefüllt wird. Gibt es eine elegante Lösung für den Umgang damit?Sammeln von API-Returns in einem Array

var itemIds = ['1','2','3','4','5','6'] 

exports.getItemData = function getItemData(req, res) { 
    var items = []; 
    var errors = []; 

    for(var itemId in itemIds) { 
     var options = { 
      uri: itemEndpoint + itemIds[itemId] +'/', 
      json: true 
     }; 

     RequestPromise(options).then(function (item){ 
      console.log(item); 
      items.push(item); 

     }).catch(function(err){ 
      console.log(err) 
      errors.push(err); 

     }); 
    }; 
    res.type('application/json'); 
    res.json(items); 
}; 
+3

['Promise.all'] (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all). –

Antwort

3

Felix hat Recht. Sie müssen ein Array von RequestPromise(options) Promises erstellen und dann das Promise.all([array-of-promises]).then(function (<array-of-result-arrays>){}) verwenden.

Also Sie überarbeitet Code wird wie folgt aussehen:

var allPromises = []; 
for(var itemId in itemIds) { 
     var options = { 
      uri: itemEndpoint + itemIds[itemId] +'/', 
      json: true 
     }; 
     allPromises .push(RequestPromise(options)); 
} 
//so now you have an array of promises in allPromises. Now when they all resolve: 
Promise.all(allPromises).then(function (allResults){ 
     console.log(allResults); 
     //do whatever with the results... 
    }).catch(function(err){ 
     console.log(err) 
     errors.push(err); 
    }); 

Ich hoffe, das hilft.

+0

Arbeitete perfekt danke – CoffeePeddlerIntern

+0

Ich bin froh, dass dies geholfen hat. Wenn Sie dies noch nicht getan haben, stimmen Sie bitte die Antwort ab. Glückliche Kodierung. – ishmaelMakitla