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

时间:2014-05-24 10:50:11

标签: javascript node.js promise q

我有一个函数,需要等到一个promise被解决后再返回一个值。不幸的是,简单地使用while循环并检查promise是否被解析会占用线程并且不会让我的setTimeout函数执行它的回调。我能想到的唯一解决方案是,如果我的d.promise尚未解析为true,则告诉js为事件队列提供服务。贝娄是我的代码:

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

1 个答案:

答案 0 :(得分:1)

承诺继续.then类似常规同步代码继续;

所以,为了等待承诺解决,你不会while(promiseNotResolved),而是你做:

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