This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
After looking at and experimenting with this code I have been unable to figure out what is going on and how I can use the information that is returned.
Where is "return callback(err, res, body)" returning to?
edit:
I want to return the data stored in 'body' but its scope is only in that function thats in the call to 'request'. How do I get the data 'body' to return all the way out when i call 'makerequest' so i can use the 'body' data. I hope I am making sense
var makerequest = function(set_parameters, callback) {
....
request(URL, function(err, res, body){
return callback(err, res, body);
});
};
You access the JSON in the callback function:
makerequest(set_parameters, function(err, res, body){
//do stuff with the body here
})
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 2 years ago.
I'm doing some fetches in a promise and then consolidating my results into a response json. When I console.log it, it prints out as expected, but I'm not sure how to return it as the response.
I have something like this:
router.get('/', function(req, res) {
Promise.all([ fetch(url1); fetch(url2); ]);
}.then(function(responses) {
// Consolidate responses into one data json
console.log(data); // Prints correct object
return response; // This doesn't work
}
I tried to call res() after some async stuff finishes, inside Async.waterfall([], cb)
But as it seems, the req/res objects are not available in that scope. I call them from my callback cb.
function (req, res, next) {
var query = req.query;
async.waterfall([
async.apply(userManager.register, query.username, query.email, query.password)
], function (err, result) {
if (err)
console.log(err);
if (err && err.internal == false)
return res(err); //TypeError: res is not a function
console.log(result);
});
The only solution I have in mind is, passing the req/res to my backend, and call it there.
But that would mean that my background code needs to have a req and res object. Moreover it returns something to my server, which is also bad.
Thanks for your help.
Your issue is not about scope. It's that res is not a function so you can't call it like res(err). res is an object with methods. You can send an error response either like this which will go to the default error handler in Express:
next(err)
Or like this:
res.status(500).send("Internal Error occurred").
which sends a 500 status on the response and then sends whatever content you want to describe the error.
I can't think of any circumstance where you want to pass the res object into your backend. Your backend should fetch and return data and then your route handler should turn that data or error into a response.
I'm very new to JS and node. I am trying to return a variable from an asynchronous http request, and I recognize that the problem is the async nature of the call, but cannot figure out how to make a very simple code snippet function despite reading multiple tutorials.
Can someone please mark this up such that it works and I can digest it and modify for my own use? Should I be using the async library? I've taken a couple of attempts and haven't been able to make that work.
var request = require('request');
a = 0;
a = foo();
function foo() {
var num = 1;
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.
num = 3;
return callback(num);
})
return num;
}
console.log(a);
So I am going to assume that you are making your request correctly, and instead focus on the idea of the callback. If you try this and still need a little more help let me know.
I will try to keep this code close to what you already have:
function foo(callback){
request('http://www.google.com', function (error, response, body) {
if(error)
console.log(error);
//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.
num = 3;
callback(num);
})
}
then in order to print a 3 out you would do something like this.
foo(function(value){
console.log(value);
})
You would see the value 3 printed out in this case.
If you wanted to return more then just 3 you would need to pass them as parameters to the callback function that has been passed in. If you were to try to follow callback style more you would probably get something closer to this.
function foo(callback){
request('http://www.google.com', function (error, response, body) {
if(error)
callback(error,null);
//do what ever you need to with the response and body
num = 3;
callback(null,num);
})
}
foo(function(err, value){
if(err)
console.log(err);
console.log(value);
})
You just need to remember that with callbacks, like Rob mentions, you typically don't return. Instead, you have your function call another function that you pass in, and provide that function with parameters that your function determined.
You must/can only operate on the results of an async call within its callback because
callbacks do not return values,
callbacks do not have access to your surrounding context, so in your example num is not defined when the callback is triggered, and
you cannot know when the callback completes and thus its result is available.
In your example code, foo will always immediately return 1 irrespective of the response/body returned from request.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I would like to set a global variable and set it value from inside of node.js request module get function. Here is my code -
var req = require('request');
var server = '';
req.get('http://httpbin.org/headers',function(err,res,body){
server = res.headers.server;
console.log(body);
});
console.log(server); // result undefined
Problem is everytime I get undefined.
It's not recommended you set global in a callback.
It's better you use events for this
EDIT
app.on('serverHeader', function(data){
//do stuff
});
app.get('...', function(req, res, cb){
app.emit('serverHeader', res.headers);
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have a function in which I'm sending an email in express using express-mailer:
exports.sendEmail = function (req, res) {
// various mail server settings here //
var output = false;
app.mailer.send(
'email',
{ to: req.body.to,
subject: req.body.subject,
otherProperty: 'Other Property'
},
function (err) {
if (err) {
// handle error
console.log(err);
res.send('There was an error sending the email');
return;
}
output = true;
console.log('email send');
}
);
return output;
}
Now this code all works and it sends the email like it should. But the return value is false, even though the "email send" string is being displayed in console, so the "output = true" must be executed. From what I've read it should be possible to override a variable inside an inner function as long as you dont redeclare it with "var", so I dont understand why it is not returning true.
I'm guessing (can't tell without knowing the implementation details of app.mailer.send) that the send function is asynchronous. So while it does send the mail, the sendEmail function is returning, so you have a race condition.
A typical solution is to execute the callback on success instead of returning a success variable and then doing something with it. Or you could use deferred calls/promises http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html