[英]Creating a chain of Promises
我在理解如何使單個Promise適應Promise鏈時遇到麻煩,一旦兩個API調用都返回,該鏈就解決了。
一個人如何將下面的代碼重寫為一個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); }); }
謝謝。
如果希望這些呼叫同時運行,則可以使用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
});
您還可以通過將它們作為鏈條返回來將它們鏈接起來,但是效率不如promise.all()-方法(先執行此操作,然后執行該操作,然后再執行其他操作)。如果需要api調用的結果1代表api呼叫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);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.