0

I have the following function:

var checkExist = function(_id) {
  var t;
  car.count({
    id: _id
  }, function(err, c) {
    if (c != 0) {
        t = 0;
        console.log(t);


    } else {
        t = 1;
        console.log(t);
    }
  });
  console.log(t);
  return t;
}

The problem: 't' is undefined at the end of the function, but it changes values inside of the if/else block. Any suggestions how to solve this?

merci

Andy
  • 61,948
  • 13
  • 68
  • 95
idntr
  • 3
  • 2
  • 6
    If `car.count` is async then you're returning before anything has set `t`. This sounds more like a problem of wrapping your head around the nature of async programming. – Dave Newton Jul 31 '14 at 10:55

1 Answers1

0

OP you need to read something about async programming.

Long story short. You CAN'T somehow make it to be synchronous

var checkExist = function(_id) {
    /*async blah-blah-blah*/
    return result;
};

if(checkExist(123)) {} //THIS WON'T work

You can make your function to take a callback

var asyncCheckExist = function(_id, success, error) {
     car.count({id: _id}, function(err, result) {
         if(err) return error && error(err);

         success(result);
     });           
};

asyncCheckExist(123, function(exists) {
       if(exists) {} //THIS WILL Work
});

Anyway you should google for async programming, callbacks, callback hell, promises etc.

Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98