我想我误解了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
我究竟做错了什么?