我怎样才能得到JavaScript服务事件队列在节点

我有一个函数,需要等到一个承诺解决之前返回一个值。 不幸的是,简单地使用一个while循环,并检查是否解决承诺霸占线程,不会让我的setTimeout函数执行它的callback。 我能想到的唯一解决scheme是告诉js服务事件队列,如果我的d.promise还没有被parsing为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); 

承诺继续,然后像普通的同步代码继续;

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

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