2017-02-04 3 views
2

두 API 호출이 반환되면 해결되는 약속 체인에 단일 약속을 적용하는 방법을 이해하는 데 문제가 있습니다.약속 체인 만들기

아래 코드를 약속 체인으로 어떻게 다시 작성합니까?

function parseTweet(tweet) { 
 
    indico.sentimentHQ(tweet) 
 
    .then(function(res) { 
 
    tweetObj.sentiment = res; 
 
    }).catch(function(err) { 
 
    console.warn(err); 
 
    }); 
 

 
    indico.organizations(tweet) 
 
    .then(function(res) { 
 
    tweetObj.organization = res[0].text; 
 
    tweetObj.confidence = res[0].confidence; 
 
    }).catch(function(err) { 
 
    console.warn(err); 
 
    }); 
 
}

감사합니다.

답변

5

통화를 동시에 실행하려면 Promise.all을 사용할 수 있습니다.) (

Promise.all([indico.sentimentHQ(tweet), indico.organizations(tweet)]) 
    .then(values => { 
    // handle responses here, will be called when both calls are successful 
    // values will be an array of responses [sentimentHQResponse, organizationsResponse] 
    }) 
    .catch(err => { 
    // if either of the calls reject the catch will be triggered 
    }); 
+0

간단하고 간단합니다. +1 –

+0

감사합니다. – Dotnaught

0

는 또한 사슬로 반환하여 그들을 체인 수 있지만 promise.all만큼 효율적이지 - 접근 방식을 (이것은 단지 그 이것을 수행되는 다른, 무언가 등) 당신이 만약을 api-call 1의 결과가 필요합니다. api-call 2에 대한 호출이 필요합니다.

function parseTweet(tweet) { 

    indico.sentimentHQ(tweet).then(function(res) { 

    tweetObj.sentiment = res; 

    //maybe even catch this first promise error and continue anyway 
    /*}).catch(function(err){ 

    console.warn(err); 
    console.info('returning after error anyway'); 

    return true; //continues the promise chain after catching the error 

}).then(function(){ 

    */ 
    return indico.organizations(tweet); 


    }).then(function(res){ 

    tweetObj.organization = res[0].text; 
    tweetObj.confidence = res[0].confidence; 

    }).catch(function(err) { 

    console.warn(err); 

    }); 

}