如何在Javascript中包装异步调用?

时间:2014-06-11 22:01:02

标签: javascript asynchronous

我希望有三个功能可以做到这样:

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;
  });
)

以上显然不会起作用,我该如何解决这个问题呢?谢谢

1 个答案:

答案 0 :(得分:0)

由于你不能return synchronously from async 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);
  });
}

但是,您可以应用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
  });
}