我有一个函数,需要等到解决承诺后再返回值。不幸的是,仅使用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
});
关于javascript - 我如何获取javascript服务 Node 中的事件队列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23844099/