[英]Creating a chain of Promises
I'm having trouble understanding how to adapt single Promises to a chain of Promises that resolves once both API calls have returned. 我在理解如何使单个Promise适应Promise链时遇到麻烦,一旦两个API调用都返回,该链就解决了。
How would one rewrite the code below to be a chain of 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); }); }
Thanks. 谢谢。
If you want the calls to run concurrently then you can use Promise.all . 如果希望这些呼叫同时运行,则可以使用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
});
You can also chain them by returning them as a chain but it is not as efficient as the promise.all() - approach (This is just do this, then that, then something else etc) If you need the result of api-call 1 for api-call 2 this would be the way to go: 您还可以通过将它们作为链条返回来将它们链接起来,但是效率不如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.