これは異なる質問ですが、私はこれを解決することができません。重複しないようにしてください。nodejs非同期モジュールの使い方は?
私は関数外の変数opにアクセスできません。 nodjesの非同期モジュールを使用する必要がありますか? 私は2つのconsole.logを持っています。しかし、機能ログ内でのみ動作します。
私は他の質問の回答を試みました。
var op = []; //declaring outside function
それはその後のHTTPモジュールのに.get()関数を呼び出し、options
それを通過して:まだそれは
var http = require('http');
console.log("hi")
var options = {
host: 'api.usergrid.com',
path: '/siddharth1/sandbox/restaurants'
};
var op = []; //declaring outside function
var req = http.get(options, function(res) {
// Buffer the body entirely for processing as a whole.
var bodyChunks = [];
res.on('data', function(chunk) {
// You can process streamed parts here...
bodyChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(bodyChunks);
// ...and/or process the entire body here.
var body2 = JSON.parse(body);
op = body2.entities.map(function(item) {
return item.name;
});
console.log(op); // only this works
})
});
req.on('error', function(e) {
console.log('ERROR: ' + e.message);
});
console.log("outside function " + op); //this doesnt work
console.log('Server listening on port 80');
console.logが正常に動作しないのは、コールバックがサーバーから返される前に実行されているためです。ここでの本当の疑問は、コールバック以外の値を調べる必要がある理由です。非同期の使用について説明する前に、それに答えてみましょう。 –