简体   繁体   中英

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.

How would one rewrite the code below to be a chain of 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([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:

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

  });

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM