我想我误解了如何Q https://github.com/kriskowal/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'); });
该代码产生:
$ 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
直接在then()
将立即触发超时,而不是给 Q 机会等待task one
做完了。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)