【问题标题】:Creating a chain of Promises创建一个 Promise 链
【发布时间】:2017-06-22 02:18:06
【问题描述】:

我无法理解如何将单个 Promise 调整为在两个 API 调用都返回后解决的 Promise 链。

如何将下面的代码重写为一系列 Promise?

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

谢谢。

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    如果您希望调用同时运行,则可以使用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
      });
    

    【讨论】:

    • 简短、简单、直接的答案! +1
    【解决方案2】:

    您也可以通过将它们作为链返回来链接它们,但它不如 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);
    
      });
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-21
      • 1970-01-01
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      相关资源
      最近更新 更多