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'); });
This code produces:
$ node test.js
starting task one
starting task two
done with task one
done with task two
all done
I would hope that it produces:
$ node test.js
starting task one
done with task one
starting task two
done with task two
all done
What am I doing wrong?
This works:
doWork('task one')
.then(function() {
return doWork('task two')
})
.then(function() {
console.log('all done');
});
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.
The reason is that the doWork needs to be referenced as a function. If you want to reference a function inside the '.then' then you just give the function name, you don't pass the parameters. When the parser sees .then(doWork('taskTwo'))it will run doWork('taskTwo') BEFORE the .then is even evaluated. It's trying to bind the function parameter.
In this case, if you return the parameter for the next task in the resolved promise of the previous task then the parser will call doWork with the correct parameter and in the correct order.
var Q = require('q');
function doWork(taskNum) {
var deferred = Q.defer();
console.log('starting', taskNum);
setTimeout(function() {
console.log('done with task', taskNum);
deferred.resolve(++taskNum);
});
return deferred.promise;
}
doWork(1)
.then(doWork)
.then(function(lastTaskNum) { console.log('all done'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With