2016-07-25 10 views
0

私はサードパーティのAPIを呼び出しています。すべての返品を収集し、APIで1つの配列として返すのに問題があります。私は通話を成功させていることがわかり、彼らは帰ってきています。 asynchのため、最後の配列は、データが格納される前に戻っています。これを処理するためのエレガントなソリューションはありますか?配列内にApiが返される

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)。 –

答えて

3

フェリックスが正しい。 RequestPromise(options)約束の配列を作成し、Promise.all([array-of-promises]).then(function (<array-of-result-arrays>){})を使用する必要があります。

だからあなたのリファクタリング、コードは次のようになります。

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); 
    }); 

私はこのことができます願っています。

+0

ありがとうございました – CoffeePeddlerIntern

+0

私はこれが助けてうれしいです。まだ行っていない場合は、その投票に投票してください。ハッピーコーディング。 – ishmaelMakitla

関連する問題