Reputation: 33
I have a problem getting the restaurantname from the db with node.js, it seems it has to do something with callback parameters but I can’t find the solution for my case, hopefully one of you can help me .
I have made function who gets the name of the restaurant from a database. The first console log line gives the right retvalue and the second one gives undefined, how can I write the code so that the return value is the name of the restaurant?
Kind regards, Robert
function restaurantName(id) {
var retvalue;
try {
F.model('restaurant').load(id).then(function (restaurant) {
retvalue = restaurant.Name;
console.log('restaurantName 1(' + id + ')' + retvalue);
})
} catch (err) {
retvalue = 'Error';
}
console.log('restaurantName 2(' + id + ')' + retvalue);
return retvalue;
};
Upvotes: 3
Views: 7144
Reputation: 7411
Your function getting data from database is asynchronous, so the second console.log
as well as return
statement are done before the database operation finishes executing. You should return the value inside .then()
function restaurantName(id) {
var retvalue;
return F.model('restaurant').load(id).then(function (restaurant) {
retvalue = restaurant.Name;
console.log('restaurantName 1(' + id + ')' + retvalue);
return retvalue;
}).catch(function(error){
return 'Error';
});
};
And this function will also return a promise
, so you would have to call it like that
restaurantName(1).then(function(result){
console.log(result); // result would be retValue or 'Error'
});
EDIT
Your second problem, mentioned in a comment below this answer, is also concerned with how the promises work. In this case I recommend you use Promise.all
method which resolves when all of the promises passed as an argument will resolve
let promises = [];
snapshot.forEach(u => {
let item = u.val();
item.key = u.key;
promises.push(restaurantName(item.restaurant).then(function(result){
item.restaurantName = result;
return item;
}));
});
Promise.all(promises).then(result => {
console.log(result); // here you get array of items
});
What happens here is you create an array of promises that resolve with given value (which in this case is item
object every time). When you pass this array to Promise.all
method, it resolves to array of values that every single promise resolved to (if no error occurs of course)
Upvotes: 6