2016-07-25 3 views
0

제 3 자 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