'How can I assign local variables in node js
I make a mailer with nodejs but i have some problems.
var smtpSender;
var smtpMailAdress;
ipcMain.on("mail:send", (err, data) => {
db.query("SELECT * FROM mail_accounts", (error, results, fields) => {
var string=JSON.stringify(results);
var json = JSON.parse(string);
smtpSender = nodemailer.createTransport({
host: json[0].host,
port: json[0].port,
auth: {
user: json[0].username,
pass: json[0].password
}
});
smtpMailAdress = json[0].username
});
console.log(smtpSender);
console.log(smtpMailAdress);
});
smtpSender and smtpMailAdress is not updated it still undefined. How can i figure it.Thanks.
Solution 1:[1]
db.query is asynchronous which means that when it is triggered, the runtime keeps going forward, while its callback function gets executed when the database sends back the results.
Here is what happens for the runtime executor:
- triggers
db.query - logs
smtpSender-> undefined - logs
smtpMailAdress-> undefined - executes
db.query's callback which modifies the content ofsmtpSenderandsmtpMailAdress
If you move the console.logs in the callback, it will work. However, it is probably not what you want, because you may not want to move your entire code inside the callback.
A simple way to handle this is to promisify your call to the database and await its completion:
var smtpSender;
var smtpMailAdress;
ipcMain.on('mail:send', async (err, data) => {
await new Promise((resolve) => {
db.query('SELECT * FROM mail_accounts', (error, results, fields) => {
var string = JSON.stringify(results);
var json = JSON.parse(string);
smtpSender = nodemailer.createTransport({
host: json[0].host,
port: json[0].port,
auth: {
user: json[0].username,
pass: json[0].password,
},
});
smtpMailAdress = json[0].username;
resolve();
});
});
console.log(smtpSender);
console.log(smtpMailAdress);
});
Solution 2:[2]
This solution is better if you want just pint to the console your vars:
var smtpSender;
var smtpMailAdress;
ipcMain.on("mail:send", (err, data) => {
db.query("SELECT * FROM mail_accounts", (error, results, fields) => {
var string=JSON.stringify(results);
var json = JSON.parse(string);
smtpSender = nodemailer.createTransport({
host: json[0].host,
port: json[0].port,
auth: {
user: json[0].username,
pass: json[0].password
}
});
smtpMailAdress = json[0].username
console.log(smtpSender);
console.log(smtpMailAdress);
});
});
By doing like this, you don't break asynchronous execution provide by node.js, is better for performance and for server health.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ben |
| Solution 2 | Alaindeseine |
