10 ms·
I would argue that reasoning about promise chains are difficult enough to where an abstraction is desirable. If you asked me to identify the most maintainable
by olingern 8y ago
I would argue that reasoning about promise chains are difficult enough to where an abstraction is desirable.
If you asked me to identify the most maintainable and easy to read of these two pieces of code, I would say the answer is easy.
Promises:
const p1, p2 = undefined;
somePromise()
.then((res) => {
p1 = somePromise(res);
return anotherPromiseFuncThatNeedsP1(p1);
})
.then((anotherPromiseRes) => {
p2 = anotherPromiseRes;
return p2;
})
.catch(e => {
// log, throw etc.
});
// done
vs
try/catch:
try {
const p1 = await somePromise();
const p2 = await anotherPromiseFuncThatNeedsP1(p1);
// done
} catch(e) {
// log, throw, etc.
}
- beojan 8y agoPut another way, monadic error handling really requires `do` notation.
- olingern 8y agoIn general, I would agree. I'm sure there are cases where Promises are still superior, but I think our brains work easier in the x = y sort of notation.
- likeclockwork 8y agoYour first example is pretty malformed. If you're promise-chaining why would you be trying to assign to variables in the outer scope? Why are you assigning to constants? Why are you calling somePromise a second time in the first then? It's almost a strawman. Anyone would have written: somePromise() .then(anotherPromiseFuncThatNeedsP1) .catch(e => whatever);
- olingern 8y ago- re: const assignments: you're correct. I did not compile this and the assignments should use let. - Show me where you have access to p1 outside of your closure. The idea is / was -- you need access to both p1 and p2 for some comparison. The first `somePromise` would have been more accurately written `someInitalPromise` The point is that try/catch + async & await removes a lot of cognitive overhead. Before async/await I rarely used try/catch -- so it's easy to get things done without it, but the combination of the two aforementioned has made codebases I work on much easier to maintain.