bendrucker / ama

Ask me questions about building web applications
MIT License
6 stars 1 forks source link

Promise patterns #16

Closed bsiddiqui closed 9 years ago

bsiddiqui commented 9 years ago

If you have a function you want to call on the result of a promise, is there any downside to adding it to the promise chain?

i.e. given some format function that doesn't return a promise

format = function (user) {
   return { ... }
}

is there any reason you should do

return User.forge({ id: id }).fetch()
.then(function (user) {
   reply(format(user))
}, reply)

instead of

return User.forge({ id: id }).fetch()
.then(format)
.then(reply, reply)

the former avoids adding another promise to the chain but the ladder looks cleaner

bendrucker commented 9 years ago

You should take advantage of Promises for readable flow control and go with the latter style. A good promise library (e.g. Bluebird) will realize that format isn't returning a thenable and introduce some performance optimizations.

bsiddiqui commented 9 years ago

👍