Q承诺的串行执行 [英] Serial execution with Q promises
本文介绍了Q承诺的串行执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我认为我误解了 Q 承诺如何运作。我希望我的第一个承诺在下一个开始之前解决,但那不会发生。这是我的代码:
I think I'm misunderstanding how Q promises work. I want my first promise to resolve before the next one starts, but that's not happening. Here is my code:
var Q = require('q');
function doWork(taskName) {
var deferred = Q.defer();
console.log('starting', taskName);
setTimeout(function() {
console.log('done with', taskName);
deferred.resolve();
});
return deferred.promise;
}
doWork('task one')
.then(doWork('task two'))
.then(function() { console.log('all done'); });
此代码生成:
$ node test.js
starting task one
starting task two
done with task one
done with task two
all done
我希望它能产生:
$ node test.js
starting task one
done with task one
starting task two
done with task two
all done
我做错了什么?
推荐答案
这有效:
doWork('task one')
.then(function() {
return doWork('task two')
})
.then(function() {
console.log('all done');
});
这是有道理的 - 只需直接调用 doWork
在然后()
将立即触发超时,而不是让Q有机会等到任务1
完成。
That makes sense - just calling doWork
directly in then()
will fire off the timeout immediately, instead of giving Q a chance to wait until task one
is complete.
这篇关于Q承诺的串行执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文