Global Variable not updating from request get function [duplicate] - javascript

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);
});

Related

Node.js writing parse data to a variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I'm writng a node.js app to read messages from Serial Port. Reading data and logging it into console works fine, althought I'm wondering how to save data value from Serial Port to a variable. I want to pass it further to a MySQL, so I need the data to be stored in variable.
I tried to use global variable, but it keeps saying "undefined". I also tried to pass the value using return in js function, but it doesn't work too. Here's my code:
var SerialPort = require('serialport');
const parsers = SerialPort.parsers;
const parser = new parsers.Readline({
delimiter: '\r\n'
});
var port = new SerialPort('COM10',{
baudRate: 9600,
dataBits: 8,
parity: 'none',
stopBits: 1,
flowControl: false
});
port.pipe(parser);
parser.on('data', function(data) {
console.log('Received data from port: ' + data);
});
Please tell me how to store data from parser.on in a variable.
Doesn't variable = data;work?

Promise with fetch returning response [duplicate]

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
}

How Do I Save The Connection Socket Writing Later In Nodejs? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I'm trying to keep a tcp socket open after it successfully connects so I can write something through it later. Here is my attempt at doing that:
var sock = null;
var server = require('net').createServer( function (socket) {
sock = socket;
socket.on('data', function (data) {
console.log(data.toString());
});
});
server.listen(10005);
if (sock != null) {
sock.write('command', 'utf-8');
else {
console.log('sock is null');
}
I didn't realize it's asynchronous so the null check on sock happens first before the connectionCallback. I came from a C++ background so this is how I was trained to think program-atically. What is the proper way to do this in javascript?
I want the user to be able to write data through the connection socket. I want to reuse that same socket that was successfully connected for writing.
Thanks.
Instead of storing socket in a variable I would write a function to handle writing that would be called when the socket is created. Something like this:
function handleSocket(socket) {
socket.write('command', 'utf-8')
}
var server = require('net').createServer(function (socket) {
socket.on('data', function (data) {
console.log(data.toString());
});
handleSocket(socket);
});
server.listen(10005);
I am not sure what else you want to do with the socket, but the pattern would be the same - you get some data and conditionally call some callback.

Function expression, returning callback function [duplicate]

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
})

Returning value from inner function in javascript [duplicate]

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

Categories

Resources