2017-11-10 3 views
0

リクエストnpmモジュールを使用しており、メインストリームリクエストの中で4リクエストを行っています。結論を最初に言うには、4つの要求のうち2つだけがランダムに成功する。リクエストnpmモジュール - リクエストの中でリクエストする

以下は私のコードです。

router.get('/', function(req, res){ 
    //TODO 
    request(url, function(error, response, body) { 
     if(err) throw error; 
     //TODO- 
     request(comnURL, function(errp,resp, body){ 
      if(errp) throw errp; 
      comnBODY = body; 
      console.log(body); 
      console.log("\n\n"); 
     }); 
     request(intrURL, function(errp,resp, body){ 
      if(errp) throw errp; 
      intrBODY = body; 
      console.log(body); 
      console.log("\n\n"); 
     }); 
     request(reptURL, function(errp,resp, body){ 
      if(errp) throw errp; 
      reptBODY = body; 
      console.log(body); 
      console.log("\n\n"); 
     }); 
     request(addiURL, function(errp,resp, body){ 
      if(errp) throw errp; 
      addiBODY = body; 
      console.log(body); 
      console.log("\n\n"); 
     }); 
     //TODO- 
    }); 
}); 

すべての応答要求はランダムに異なり、2つのサブ要求のうちの2つを選択します。これの理由とその回避方法を教えてください。

答えて

1

コードに構文エラーがありますが、問題なく動作します。これは非同期の問題です。あなたは順番に実行し、この4要求をしたい場合は、この方法で置く必要があります:あなたはrequest-promise moduleを使用することができ、そのために

'use strict'; 

const request = require('request') 

request('https://jsonplaceholder.typicode.com/posts/5', function(error, response, body) { 
    if(error) throw error; 
    //TODO- 
    request('https://jsonplaceholder.typicode.com/posts/1', function(errp,resp, body){ 
     if(errp) throw errp; 
     let comnBODY = body; 
     console.log(body); 
     console.log("1\n\n"); 
     request('https://jsonplaceholder.typicode.com/posts/2', function(errp,resp, body){ 
      if(errp) throw errp; 
      let intrBODY = body; 
      console.log(body); 
      console.log("2\n\n"); 
      request('https://jsonplaceholder.typicode.com/posts/3', function(errp,resp, body){ 
       if(errp) throw errp; 
       let reptBODY = body;   
       console.log(body); 
       console.log("3\n\n"); 
       request('https://jsonplaceholder.typicode.com/posts/4', function(errp,resp, body){ 
        if(errp) throw errp; 
        let addiBODY = body; 
        console.log(body); 
        console.log("4\n\n"); 
       }); 
      }); 
     }); 
    }); 
}); 

別のアプローチは、約束の方法を使用しています。

関連する問題