4 ms·
I think your examples could be simplified: export default function getUsers () { return getUsersFromDB() .then(filterUsersWithFriends) .t
by phpnode 10y ago
I think your examples could be simplified:
export default function getUsers () {
return getUsersFromDB()
.then(filterUsersWithFriends)
.then(getUsersLikes);
}
And there's just about never a reason to use the `Promise` constructor in real world code. If you already have a promise as in your example, so you can rewrite your refactoring as:
export default function getUsers () {
return getUsersFromDB()
.then(users => filterUsersWithFriends(users).catch(err => trySomethingElse(users)));
}
- inglor 10y agoAKA the explicit construction anti-pattern: stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it/23803744
- krisdol 10y ago> And there's just about never a reason to use the `Promise` constructor in real world code Why not? If I want to wrap a callback function in a promised sequence, I don't see a way around it. Please don't suggest importing bluebird/promisifyAll because that only teaches me how to avoid thinking about the problem, not how it's actually solved, let alone why it's a problem to begin with. function promiseMeFoo() { return new Promise((resolve, reject) => { asynchronousFoo((err, out) => { if (err) return reject(err); return resolve(out) }); }); } ^ aside from just rearranging the code for legibility, how can I do the same thing without constructing a promise explicitly?
- phpnode 10y agoBluebird's `promisifyAll()` is just a way to generalize that pattern, so that you don't need to write it yourself. And if you care about performance it's substantially faster too. If you want to learn about the pattern then fine, but personally I don't want to write that for every single `fs` function I use in a project, it's much more convenient to just `Bluebird.promisifyAll(require('fs'))`.
- WorldMaker 10y agoAlso libraries like `promise-ring` that just do this one thing without needing all of bluebird installed.
- spion 10y agoI came here to post the same thing :) Indeed, pretty much any imperative control flow construct you can think of has a very similar method-based equivalent with promises.
- djokkataja 10y agoI noticed this as well. On the other hand, even though the example the author provided could be substantially simplified as you showed, if you wanted to later on refactor the `getUsers` function again to add more logic, your promises code would end up more and more contorted. In practice I've found `await` and `async` to hugely simplify these kinds of complex promises.
- spion 10y agoI have the opposite experience of that. Generally function-based promise code is just about the same as async/await. It does take some time to get used to all the equivalencies between imperative code and promises though.