When working with Bluebird promises in Bookshelf, developers often employ a pattern similar to the one below:
var getEvents = function(participantId) { return new models.Participant() .query({where: {id: participantId}}) .fetch({withRelated: ['events'], require: true}) .then(function(model) { return model; }); };
However, this code raises questions for those unfamiliar with promises. Does the then function have any meaningful impact on the overall behavior of the code? Could the following implementation achieve the same result without it?
var getEvents = function(participantId) { return new models.Participant() .query({where: {id: participantId}}) .fetch({withRelated: ['events'], require: true}); };
The crux of the matter lies in the function parameter passed to then. This argument is expected to receive the return value of the preceding promise in the chain. Thus, it appears that the return a; statement within the then function is essentially a no-op, as it merely passes through the received argument unchanged.
Despite its apparent redundancy, the then function serves a purpose in certain use cases. One example is when the returned promise needs to be treated differently down the chain. For instance, it could be logged, converted to JSON, or handled in a custom way. Another advantage is that the then function allows for error handling, although this could also be achieved through done, depending on the promise library employed.
In general, it is advisable to only use then when it is genuinely required. Unnecessary then functions can add unneeded complexity to the codebase and increase the potential for errors. As a general rule of thumb, only incorporate then when the returned promise's result or error needs to be explicitly modified or processed.
The above is the detailed content of Does '.then(function(a){ return a; })' Actually Do Anything for Promises?. For more information, please follow other related articles on the PHP Chinese website!