Resolving a Promise without calling the 'then'

和自甴很熟 提交于 2019-12-06 02:33:06

It's actually very straightforward. Only you may have missed it because it's hidden amongst that tangle of code.

Basically you do this:

var promise = new Promise(function (resolve, reject) { /*....*/});

if (typeof cb === 'function') {
    promise.then(cb);
} else {
    return promise;
}

Actually, it's a pretty common thing APIs do (mongodb-driver example). Basically, write a private function accepting a callback, write a public function checking for cb and writing it if necessary. Using the code from your github (_any might need a refactoring, you don't need to check if cb is a function for example and maybe other things too):

 // private function
var _any = function(msg, cb) {
  if (this.kill) {
    console.log('warning: pool.any called on pool of dead/dying workers');
    return;
  }

  debug('current available pool size for pool_id ' + this.pool_id + ' is: ' + this.available.length);
  var workId = this.counter++;

  if (typeof cb === 'function') {
    this.resolutions.push({
      workId: workId,
      cb: cb
    });
  } else {
    workId = -1;
  }

  if (this.available.length > 0) {
    var cp = this.available.shift();
    cp.workId = workId;
    cp.send(msg);
  } else {
    this.msgQueue.push({
      workId: workId,
      msg: msg
    });
  }
};

 // public exposed function
Pool.prototype.any = function(msg, cb) {
  if (typeof cb === 'function') {
    // cb is provided, no action is required here
    return _any(msg, cb);
  } 

  // no cb, wrap the call inside a Promise and provide a cb
  return new Promise(function(resolve, reject) {
    _any(msg, function(err, data) {
      if (err) reject(err);
      else resolve(data);
    });
  });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!