2016-06-02 7 views
1

複数のリクエストを(Expressを使用して)送信し、すべてのレスポンスを1つの関数で処理する方法を見つけようとしています。NodeJS - 複数のリクエストを送信し、すべての応答を1つのコールバックで処理する

// In router.js 
    app.get('/api/FIRST_PATH', CALLBACK_FUNCTION_A); 

// In CALLBACK_FUNCTION_A file : 
module.exports = function (req, response) { 
    CALLBACK_FUNCTION_TO_SERVICE_A(); 
    CALLBACK_FUNCTION_TO_SERVICE_B(); 
    CALLBACK_FUNCTION_TO_SERVICE_C(); 
} 

私の問題は、要求CALLBACK_FUNCTION_TO_SERVICE_A、CALLBACK_FUNCTION_TO_SERVICE_BとCALLBACK_FUNCTION_TO_SERVICE_Cを送信し、それらを処理するために別の関数内のすべての結果を取得することです:

は、ここに私のコードです。

ご協力いただければ幸いです。

+1

約束を返す要求を行うには[request-promise](https://www.npmjs.com/package/request-promise)を使用し、その後約束が完了したら何かをしてください。 –

答えて

1

新しいjs標準の詳細については、Promiseをご利用ください。もちろんCALLBACK_FUNCTION_TO_SERVICE_A()Promiseオブジェクトを返すために、そのような必要性

// In CALLBACK_FUNCTION_A file : 
module.exports = function (req, response) { 
    var promises = [CALLBACK_FUNCTION_TO_SERVICE_A(), 
     CALLBACK_FUNCTION_TO_SERVICE_B(), 
     CALLBACK_FUNCTION_TO_SERVICE_C()]; 

    Promise.all(promises).then(function(results) { 
     //results is an array 
     //results[0] contains the result of A, and so on 
    }); 
} 

。あなたはこのような関数を形成:

function asyncFunction(callback) { 
    //... 
    callback(result); 
} 

あなたはこのような約束を作成することができます:

var p = new Promise(asyncFunction); 

それは、機能の実行を開始し、約束のインタフェースをサポートしています。

したがって、たとえば、request-promiseを使用するかのような何かを行うことができますいずれか:あなたはPromise、どのようにも簡単にエラーを処理する方法についての詳細を読むことができます

function CALLBACK_FUNCTION_TO_SERVICE_A() { 
    var worker = function(callback) { 
     app.get('/api/FIRST_PATH', callback); 
    }; 

    return new Promise(worker); 
} 

を。

+0

マインドブロー!どうもありがとう –

1

async parallelを使用できます。すべてのAPI呼び出しをasync.parallel配列またはJSON(例では配列を使用)として保持できます。

async.parallel(
[ 
    function(done){ 
     reqServcieA(..., funnction(err, response){ 
     if(err) done(err,null); 
     done(null, response); 
     } 
    }, 
    function(done){ 
     reqServcieA(..., funnction(err, response){ 
     if(err) done(err,null); 
     done(null, response); 
     } 
    }, 
    ...// You can keep as many request inside the array 

], function(err,results){ 
    // Will be called when all requests are returned 
    //results is an array which will contain all responses as in request arry 
    //results[0] will have response from requestA and so on 
}); 
+0

私はasync parrallelを使ってみました。私はそれを正しく使用しなかったと思います。答えてくれてありがとう。 –

関連する問題