我想我误解了Q承诺如何运作.我希望我的第一个承诺在下一个开始之前解决,但那不会发生.这是我的代码:
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'); });
Run Code Online (Sandbox Code Playgroud)
此代码生成:
$ node test.js
starting task one
starting task two
done with task one
done with task two
all done
Run Code Online (Sandbox Code Playgroud)
我希望它能产生:
$ node test.js
starting task one
done with task one
starting task two
done with task two
all done
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
这有效:
doWork('task one')
.then(function() {
return doWork('task two')
})
.then(function() {
console.log('all done');
});
Run Code Online (Sandbox Code Playgroud)
这是有道理的 - 只是doWork直接调用then()将立即触发超时,而不是让Q有机会等到task one完成.
| 归档时间: |
|
| 查看次数: |
2833 次 |
| 最近记录: |