Das ist eine andere Frage und ich kann keine Lösung dafür finden, bitte markieren Sie es nicht doppelt.Wie nodejs async Modul zu verwenden?
Ich kann außerhalb der Funktion auf Variable op nicht zugreifen. Sollte ich ein Async-Modul von nodjes verwenden? Ich habe zwei console.logs. Aber nur innerhalb des Funktionsprotokolls funktioniert.
Ich habe andere Fragen Antworten versucht. Dennoch ist es nicht
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');
Das console.log, das nicht funktioniert, funktioniert nicht, da es ausgeführt wird, bevor der Rückruf vom Server zurückkehrt. Die wirkliche Frage hier ist, warum müssen Sie den Wert außerhalb des Rückrufs betrachten? Lassen Sie uns das beantworten, bevor wir über die Verwendung von Async sprechen. –