Reputation: 105
How can I get this value when I get a response from the server?
The terminal is not outputing any information when I run it.
console.log(a);
function findMaxID() {
var a = needle.get(URL, function(err, res){
if (err) throw err;
return 222;
});
return a;
}
Upvotes: 1
Views: 7013
Reputation: 2704
Basicly, you can't really return
this value in the way functions return values. what you CAN do is give your findMaxID()
function a callback parameter to be called when the data is fetched :
function findMaxID(callback) {
needle.get(URL, function(err, res){
if (err) throw err;
callback(res);
});
}
then call it like this :
findMaxID(function(id) {
console.log('Max ID is : ', id);
}
You can also return a promise :
function findMaxID() {
return new Promise(function (resolve, reject) {
needle.get(URL, function(err, res){
if (err) reject(err);
resolve(res);
});
});
}
And call it like this :
findMaxID().then(function(id) {
console.log('Max ID is ', id);
})
Or like this if you're under an async
function :
var id = await findMaxId();
console.log(id); // logs the ID
Upvotes: 5