Assuming Node.js and Q, take the following code:
return promise1()
.then(function promise2(resultOfPromise1) {
return resultOfPromise1 + 1;
}).then(function promise3(resultOfPromise2) {
return resultOfPromise2 + 1;
}).then(function promise4(resultOfPromise3) {
return resultOfPromise3 + 1;
})
Promises (at least in Q) are designed for this sort of design pattern. However, often in my code, I run into situations where there is a similar flow of dependencies, but the final promise needs data from all the previous promises. So for example:
return promise1()
.then(function promise2(resultOfPromise1) {
return resultOfPromise1 + 1;
}).then(function promise3(resultOfPromise2) {
return resultOfPromise2 + 1;
}).then(function promise4(resultOfPromise3) {
return [resultOfPromise1, resultOfPromise2, resultOfPromise3];
})
Of course, promise4()
doesn't have resultOfPromise1
and resultOfPromise2
in its scope. One solution to this is simply nesting the promises, but that's the one of the problems promises came to solve in replacing callbacks.
Another is to have a top-level variable in the scope of promise1()
, and store all the return values of the promises to that, and then access that in promise4()
. But that solution is messy and difficult to read.
So far I've been using the nesting method, but it isn't ideal. Is this something you run into in your code as well? What is a better way to achieve this?
Aucun commentaire:
Enregistrer un commentaire