繁体   English   中英

我如何获取javascript服务节点中的事件队列

[英]How can I get javascript to service event queue in node

我有一个函数,需要等到解决承诺后再返回值。 不幸的是,仅使用一个while循环并检查是否已解决了诺言,就使线程陷入困境,并且不会让我的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);

承诺继续.then有点像定期同步码连续用;

因此,为了等待一个诺言解决,您不执行while(promiseNotResolved) ,而是执行:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM