-1

I'm trying to set some variables in node js like this:

var perm1 = 0;
var perm2 = 0;
check_tasksAssigned(data,function(resp1) {
    perm1 = resp1;
});
check_projectMembers(data,function(resp2) {
    perm2 = resp2;
});

if(perm1 && perm2) {
    // do some db stuff here
}

But I'm getting as undefined. I also tried like this:

var perm1 = check_tasksAssigned(data,function(resp1) {
                        
});
var perm2 = check_projectMembers(data,function(resp1) {
                        
});

if(perm1 && perm2) {
    // do some db stuff here
}

And have tried like this, but the result is same in all cases:

var perm1 = check_tasksAssigned(data);
var perm2 = check_projectMembers(data);

if(perm1 && perm2) {
    // do some db stuff here
}

How do I solve this?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Niranjan N Raju
  • 12,047
  • 4
  • 22
  • 41

1 Answers1

5

The best way is to use a promises library. But the short version might look like:

var perm1 = 0;
var perm2 = 0;
check_tasksAssigned(data,function(resp1) {
    perm1 = resp1;
    finish();
});
check_projectMembers(data,function(resp2) {
    perm2 = resp2;
    finish();
});

function finish() {
if(perm1 && perm2) {
    // do some db stuff here
}
}

EDIT

By request, with promises, this code would look something like:

when.all([
  check_tasksAssigned(data)
    .then(function(resp1) {
      perm1 = resp1;
    }),
  check_projectMembers(data)
    .then(function(resp2) {
       perm2 = resp2;
    })
  ])
  .then(finish);

But there are many ways of expressing this, depending on the exact promises library, etc.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Steve Bennett
  • 114,604
  • 39
  • 168
  • 219