2017-02-04 4 views
2

APIコールが返された後に解決するプロミスチェーンに単一プロミスを適用する方法を理解できない。プロミスチェーンの作成

以下のコードを約束のチェーンに書き換えると、どのようになりますか?

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の結果を必要とする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); 

    }); 

} 
関連する問題