-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?

3
  • It's likely a duplicate, but I wouldn't say it's a duplicate of that one. You can get to the answer for this from there, but waiting for two results is different from just waiting for one. Commented Sep 21, 2015 at 12:26
  • This one, I think. Commented Sep 21, 2015 at 12:28
  • Thank you for your replay, i will check the link. Commented Sep 21, 2015 at 12:33

1 Answer 1

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.

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

1 Comment

Curious to see how this could be achieved using Promise!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.