2017-11-23 1 views
0

나는호출 API를 - 각도 JS는

for(var i=0; i<array.length; i++) 
    service.getfunction(array[i]).then(function(response) { 
     service.getfunction1(response).then(function(response) { 
     service.getfunction2(response).then(function(response) { 
      service.getfunction3(response).then(function(response) { 
      console.log(response); 
      }); 
     }); 
     }); 
    }); 
) 

두 번째 루프는 내가 처음 루프 마지막 getfunction3의 API에서 결과를 얻었다 후에 만 ​​시작해야 for 루프 내에서 실행해야 할 API 세트가 있습니다. 어떻게해야합니까?

답변

2

첫째 - 당신은 체인 수처럼 약속 :

function doJob(i) { 
    return service.getfunction(array[i]).then(function(response) { 
    return service.getfunction1(response); 
    }).then(function(response) { 
    return service.getfunction2(response); 
    }).then(function(response) { 
    return service.getfunction3(response); 
    }).then(function(response) { 
    console.log(response); 
    }); 
} 

한 번에 해결 될 것입니다 약속을 반환합니다이 기능이 모든 서비스가 완료 호출 .

var p = Promise.resolve(true); 
for(var i = 0; i < array.length; i++) { 
    (function(idx) { //We need to wrap it or we will pass incorrect i into doJob 
    p = p.then(function() { 
     return doJob(idx); 
    }); 
    })(i); 
} 
p.then(function() { 
    console.log('Everything done'); 
}); 
+0

이 많이 단순화 할 수있는'반환 service.getfunctionX를 생략하여 그리고 지금은 그것을 사용할 수 있습니다 (응답)'. 'then'은 기본적으로 이전 약속에서 확인 된 값을 반환 할 것이므로'service.getFunction (array [i]). then (service.getfunction1) .then (service.getfunction2) .then (service. getfunction3)'... –

+0

API 중 하나라도 실패하면 어떻게됩니까? – Anna

+0

@Anna 당신은'then' 함수의 두 번째 인자를 사용하여 에러를 처리하거나'catch' 함수를 연결할 수 있습니다. 마지막'catch '이후 전체 체인에서 모든 오류를 가져옵니다. – DontRelaX

0

하는 기능에 랩 : 모든

// Declare function 
function LoopAPI() { 
    for(var i=0; i<array.length; i++) 
     service.getfunction(array[i]).then(function(response) { 
      service.getfunction1(response).then(function(response) { 
      service.getfunction2(response).then(function(response) { 
       service.getfunction3(response).then(function(response) { 
       console.log(response); 

       // Call function again 
       LoopAPI(); 
       }); 
      }); 
      }); 
     }); 
    ) 
} 

// First call 
LoopAPI(); 
0

당신은 체인의 약속은 다음과 같은 순서대로 호출하는 Array.reduce를 사용할 수 있습니다 :

array.reduce(function(previous, next) 
{ 
    return previous.then(function() 
    { 
     return service.getfunction(next); 
    }) 
    .then(function(response) 
    { 
     return service.getfunction1(response); 
    }) 
    .then(function(response) 
    { 
     return service.getfunction2(response); 
    }) 
    .then(function(response) 
    { 
     return service.getfunction3(response); 
    }); 
}, Promise.resolve()) 
.then(function() 
{ 
    console.log("All done."); 
}) 
.catch(function(error) 
{ 
    console.log(error); 
});