0

I want to have three functions that do something like this:

function getuser1(){
  var user = b();
  //do some stuff to user
  return user;
}

function getuser2(){
  var user = asyncfinduser();
  //do some different stuff to user
  return user;
}

function asyncfinduser(){
  userDB.find( { /* some criteria */ }, function (error, user) {
    //return found user to functions above
    return user;
  });
)

The above is obviously not going to work so how can I fix this? Thank you

user3409889
  • 187
  • 2
  • 11
  • Rather than returning the user from your async function to your other functions, you should pass the other functions to the async function as callbacks. – jahroy Jun 11 '14 at 22:19
  • As @jahroy suggests use callbacks, or return a `promise` from your `asyncfinduser` function. – christian314159 Jun 11 '14 at 22:58

1 Answers1

0

Since you cannot return synchronously from async callbacks, you will need to use callbacks:

function getuser1(callback) {
  asyncfinduser(function(error, user) {
    if (error) return callback(error);
    //do some stuff to user
    callback(null, user);
  });
}

function getuser2(callback) {
  asyncfinduser(function(error, user) {
    if (error) return callback(error);
    //do some different stuff to user
    callback(null, user);
  });
}

function asyncfinduser(callback) {
  userDB.find( { /* some criteria */ }, function (error, user) {
    if (error) return callback(error);
    //return found user to functions above
    callback(null, user);
  });
}

However, you might be able to apply the promise pattern:

var Promise = …; // some library

function getuser1() {
  return asyncfinduser().then(function(user) {
    //do some stuff to user
    return user;
  });
}

function getuser2() {
  return asyncfinduser().then(function(user) {
    //do some different stuff to user
    return user;
  });
}

function asyncfinduser() {
  return new Promise(function(resolve, reject) {
    userDB.find( { /* some criteria */ }, function (error, user) {
    if (error) reject(error);
    else resolve(user); //return found user to functions above
  });
}
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375