2017-02-04 32 views
2

我無法理解如何將單個Promise調整爲一旦兩個API調用都返回就解析的Promises鏈。創建Promises鏈條

如何將下面的代碼重寫爲Promises鏈?

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

    }); 

}