function returns undefined value [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have a function named IsValidUrl() that I need that returns some values by its situation(false or true). But inside of this function I have another function that won't let to pass the values to IsValidUrl().
var validUrl = await isValidUrl();
if (!validUrl) {
console.log(validUrl); ** //validUrl is undefined**
return res.status(404).send('not found');
}
function isValidUrl() {
Post.findOne({
url: req.params.path
}, function(err, result) {
if (err) {
throw err
} else if (!result) {
return false
} else {
return true
}
})
}
How can I send the returned values to the IsValidUrl()?

function isValidUrl() {
return new Promise((resolve, reject) => {
Post.findOne({
url: req.params.path
}, function(err, result) {
if (err) {
reject(err);
} else if (!result) {
resolve(false);
} else {
resolve(true);
}
})
})
}

Related

how can i get value out of a child function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
var checkAcount = (usr, pass) => {
var sql = "SELECT * FROM account WHERE userName = '" +usr+"'" ;
con.query(sql, (err, result) => {
if(err) throw err;
if(result.length > 0){
bcrypt.compare(pass, result[0].password, function(err, result1) {
if(result1 == true){
return true;
}
else{
return false;
}
});
}
else {
return false;
}
});
return ???;
}
I have code like this and I don't know how to make this function return the value of the compare function (true or false). Add return in child function like I did seem not to work. Can somebody help me please.
You could return a promise:
async function checkAcount(usr, pass) => {
const sql = "SELECT * FROM account WHERE userName = ?" ;
return new Promise((resolve, reject) => {
con.query(sql, [usr], (err, result) => {
if(err) {
reject(err);
throw err;
}
if(result.length > 0){
bcrypt.compare(pass, result[0].password, function(err, result1) {
if(result1 == true){
resolve(result);
return true;
} else{
reject(err);
return false;
}
});
} else {
reject(err);
return false;
}
});
});
}
Don't build your SQL query with string concatenation. That allows SQL injection.
bcrypt returns a promise
https://www.npmjs.com/package/bcrypt#with-promises
bcrypt.compare(pass, result[0].password).then((result) => {
return result;
})

How to pass value from asynchronous function (Node.js) [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
From my code, I want the value in _status variable after query and write file from MongoClient.connect, but I get NULL from return _status. How can I pass the value outside the function? Thank you for your answer.
function query(domain)
{
var _status;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.collection("zone").find({"name" : domain}).toArray(function(err, result) {
if (!err) {
fs.writeFile('/root/'+domain+'.txt', result, function (err) {
if (err) throw err;
});
_status = "success";
}
else {
_status = "fail";
}
});
db.close();
});
return _status;
}
You are calling asynchronous functions( MongoClient.connect, .find) inside your function query, and trying to get the result(_status) synchronously. This does not work. You can use a callback based approach or a promise based approach to let the value of _status known to the caller.
Please refer here for more on promises.
try something like that
function query(domain, callback)
{
var _status;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.collection("zone").find({"name" : domain}).toArray(function(err, result) {
if (!err) {
fs.writeFile('/root/'+domain+'.txt', result, function (err) {
if (err) throw err;
});
_status = "success";
}
else {
_status = "fail";
}
callback(_status);
});
db.close();
});
}
query(domain, (status) => {
// Synchronous
// do something
console.log(status);
});

Pass object from SQL query function to a separate function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I'm new to node and promises. I have two files - server.js and db.js
server.js imports db.js as modules.
I'm fetching some data from a SQL database in a db.js module and I'm trying to pass that data to a function in server.js.
I've successfully fetched the data from database, but when I try to pass it to the function in server.js, it only returns an undefined value.
Here's the code
server.js
const db = require('./db.js');
app.post('/api/trigger-push-msg/', function (req, res) {
return getSubscriptionsFromDatabase()
.then(function(subscriptions) {
// Do something
});
});
function getSubscriptionsFromDatabase() {
return new Promise((resolve, reject) => {
let subscriptions = db.getSubscriptions();
console.log(subscriptions); // this only prints "undefined"
if (subscriptions != undefined) {
resolve(subscriptions);
} else {
reject("No"); // this executes
}
})
}
db.js
module.exports = {
getSubscriptions: function() {
var sql = "SELECT * FROM subscriptions";
con.query(sql, function(err, result) {
if (err) throw err;
console.log(result); // this prints the same result as I want
return result;
})
}
}
getSubscriptions doesn't have a return statement
and considering that there's some async content in it you should wrap all inside a promise and trigger the subsequent logic only after it resolves.
module.exports = {
getSubscriptions: function() {
var sql = "SELECT * FROM subscriptions";
return new Promise(function(resolve, reject){
con.query(sql, function(err, result) {
if (err) return reject(err);
resolve(result);
})
})
}
}
then:
function getSubscriptionsFromDatabase() {
return db.getSubscriptions()
.then(function(subscriptions){
return subscriptions;
})
}
and in your route:
app.post('/api/trigger-push-msg/', function (req, res) {
getSubscriptionsFromDatabase()
.then(function(subscriptions) {
res.send(subscriptions);
})
.catch(function(err){
res.sendStatus(500);
})
});

JavaScript/NodeJS Callback within a callback [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm using the 'user-management' package in Node, and I have a callback within a callback, within a callback. But the final result doesn't return. This is my main NodeJS module:
playerManagement.login(data.username, data.pw, function (result) {
console.log(result) <-- statement never reached
if (result == "fail") {
socket.emit('client', { type: 'login', result : 'fail'});
} else {
connections[playerindex++] = {'username' : username, 'sockid' : socket.id, 'token' : result };
socket.emit('client', { type: 'login', result : 'success', username : username });
console.log(connections);
}
});
Then I have an external module with the function:
playerModule.prototype.login = function(username, password) {
var o = this;
o.user.load(function (err) {
if (!err) {
o.user.authenticateUser(username, password, function(err, result) {
if (!result.userExists) {
console.log('Invalid username');
return "fail";
} else if (!result.passwordsMatch) {
console.log('Invalid password');
return "fail";
} else {
console.log('User token is: ' + result.token); <--- this is reached.
return result.token;
}
});
} else {
console.log('error logging in');
return "fail";
}
});
So I'm guessing I need to return the value to the "load" function callback, but I'm not sure how to do that.
Change the definition of login with the following.
playerModule.prototype.login = function(username, password, callback) {
var o = this;
o.user.load(function (err) {
if (!err) {
o.user.authenticateUser(username, password, function(err, result) {
if (!result.userExists) {
console.log('Invalid username');
return callback("fail");
} else if (!result.passwordsMatch) {
console.log('Invalid password');
return callback("fail");
} else {
console.log('User token is: ' + result.token); <--- this is reached.
return callback(result.token);
}
});
} else {
console.log('error logging in');
return callback("fail");
}
});

Returning variable from callback into a defined function-NodeJS [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
music.playsong = function(vars){
//vars is an array with a Key named "song"
youTube.search(vars["song"], 2, function(error, result) {
if (error) {
console.log(error)
return;
}else {
console.log("Success")
return result
}
})
}
I am currently calling this function as
music.playsong(data)
However in this function I can not access the underlying callback and get the value from that. How do I get this music.playsong() to return the result of the callback without blocking execution?
You want use a async function as sync. So it's not possible. So you need to change your method to be async like this :
music.playsong = function(vars, cb){
//vars is an array with a Key named "song"
youTube.search(vars["song"], 2, function(error, result) {
if (error) {
console.log(error)
process.nextTick(() => {
cb(error)
})
}else {
console.log("Success")
process.nextTick(() => {
cb(null, result)
})
}
})
}
music.playsong = function(vars){
youTube.search(vars["song"], 2, function(error, result) {
if (error) {
return callback("Error",{});
}else {
console.log("Success")
return callback(""success",result)
}
})
}
function callback(data){
//TODO
}
It looks like that youtube.search is an asynchronous action.
In this case, you should use Promise
e.g.
music.playsong = function(vars) {
return Promise(resolve, reject) {
//vars is an array with a Key named "song"
youTube.search(vars["song"], 2, function(error, result) {
if (error) {
return reject(err);
}
console.log("Success")
return resolve(result);
}
})
}
}
music.playsong('').then(function(result) {
// you will get result here
});
In Promise, you will have resolve and reject for handling async action.
when resolve got called, it will pass data to .then
when reject got caleed, it will pass err to .catch

Categories

Resources