2017-12-04 16 views
0

ノードアプリケーション用にリクエストlib(https://www.npmjs.com/package/request)を使用します。ノードリクエストの単純な使用が動作しない

そして、この単純な例は動作しません:

console.log(' BEGIN ---- '); 
request('http://www.google.com', function (error, response, body) { 
    console.log('error:', error); // Print the error if one occurred 
    console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received 
    console.log('body:', body); // Print the HTML for the Google homepage. 
}); 
console.log('END ---- '); 

私だけは私のコンソールでメッセージ---- ----とENDをBEGINませんが、GETリクエストから何もしています。

私は何かを見逃しましたか?

答えて

0

Nodejsは、実行時にスクリプトリクエストが行くと提供されたリンクからデータを取得するためにいくつかの時間がかかりますが、それは、それが完了するため、このタスクは、したがって、他のコードが待機しません完了するまでにしばらく時間がかかりますを意味し、非同期を振る舞います。

コールバックを使用して結果を待つことができます。以下のコードは、問題の簡単な解決策です。

しかし、よりクリーンで使いやすいため

const request = require('request') 
 

 

 
function req(callback){ 
 
    console.log(' BEGIN ---- '); 
 
    request('http://www.google.com', function (error, response, body) { 
 
     console.log('error:', error); // Print the error if one occurred 
 
     console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received 
 
     console.log('body:', body); // Print the HTML for the Google homepage. 
 
     callback() 
 
    }); 
 
} 
 

 
req(function(){ 
 
    console.log('END ---- '); 
 
})

はあなたが約束またはasyncを使用することを学ぶ必要があるコードを読み取ること/ nodejsに特徴を待っています。

関連する問題