3

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;
};
3
  • Can't you keep the second console.log inside the try block? Commented Feb 16, 2017 at 15:27
  • You're not handling any error case in your callback function. Commented Feb 16, 2017 at 15:32
  • 3
    Possible duplicate of How do I return the response from an asynchronous call? Commented Feb 16, 2017 at 15:45

1 Answer 1

6

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)

Sign up to request clarification or add additional context in comments.

11 Comments

The original function call is: item.restaurantName = restaurantName(item.restaurant); I've replaced it with: restaurantName(item.restaurant).then(function (result) { console.log('result: ' + result); // result would be retValue or 'Error' item.restaurantName = result; }); The result of the call is Error in stead of the correct name (which is returned in the function)
So you have to do restaurantName(item.restaurant).then(function(result){ item.restaurantName = result; });
There was a typo in my answer, there was return retValue whereas it should be return retvalue, maybe that's the case if you got the same code as in my answer
Now the function returns the correct name and when I use it in the call it is working fine in the log(22), but before the push the variable is undefined again, do you have a solution for that? snapshot.forEach(u => { let item = u.val(); item.key = u.key; restaurantName(item.restaurant).then(function (result) { item.restaurantName = result; console.log('22 user:' + item.name + ' ' + item.restaurantName); }); console.log('24 user:' + item.name + ' ' + item.restaurantName); sorted.push(item); });
It is another issue related to how the promises work. You need to read about them and understand at least their basic concepts, otherwise you will constantly encounter similar problems. Also, read about asynchronous operations in javascript
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.