您好,我想在函数外部使用回调进行变量外部使用,但是出了点问题,我认为我的回调并不像我想的那样正确:
function latitude(callback){
var mylat;
const https = require('https');
https.get('https://url_of_my_json', (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
mylat = JSON.parse(data).results[0].geometry.location.lat;
callback(mylat);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
}
var mylat = latitude(); // variable i want to use for the rest of code
谢谢
答案 0 :(得分:0)
回调的语法不正确。
这里是示例,为了更好地了解回调,请尝试尽可能简单地阅读此示例,只需复制save newfile.js do node newfile即可运行应用程序。
function myNew(next){
console.log("Im the one who initates callback");
next("nope", "success");
}
myNew(function(err, res){
console.log("I got back from callback",err, res);
});
快乐的编码:)