我如何让javascript服务事件队列在节点



我有一个函数需要等待,直到一个承诺被解决之前返回一个值。不幸的是,简单地使用while循环并检查promise是否被解析会占用线程,并且不会让我的setTimeout函数执行它的回调。我能想到的唯一解决方案是告诉js服务事件队列,如果我的d.c promise没有被解析为true。下面是我的代码:

var _ = require('lodash');
var Q = require('q');
var h = function(x,y,z, callback) {
  setTimeout(function(){
    // This never logs to my terminal
    console.log(x + y + z);
    callback();
  }, 1000);
};
var b = function(x,y,z, callback) {
  console.log(x * y * z);
  callback();
};
chain = function(args, f) {
  var index;
  if( (index = _.indexOf(args,'cb')) < 0 ) {
          f.apply(null,args);
  } else {
      return {
        chain: function(newArgs, fxn) {
          var d = Q.defer();
          args[index] = function() {
            d.resolve(true);
          };
          f.apply(null,args);
          // Don't return until callback is resolved.
          while(d.promise.valueOf() != true){
            // Since the thread is hogged by this loop, I'd like
            // to tell it to manually service my event/function queue
            // so that setTimeout works while this loop polls.
            // This setTimeout will never execute the callback
            setTimeout(function(){console.log('hi');},5);
          };
          return chain(newArgs, fxn);
        }
      }
  }
}
chain([2,2,3,'cb'], h ).
chain([2,5,3, 'cb'], b).
chain([2,1,3,'cb'], h ).
chain([2,2,5, 'cb'], b).
chain([6,6,6, function() {console.log('ok');}], b);

承诺从.then继续,有点像常规同步代码从;继续

所以,为了等待一个承诺解决,你不做while(promiseNotResolved),相反,你做:

promise().then(function(value){
    //code that runs once the promise is resolved
});

最新更新