[2020-03-31] Promise Usage Tips
Just some personal observations while working extensively with asynchronous code and promises in particular.
In a promise
then()
function, returned values are automatically resolved, andthrow
's are automatically rejected.One extremely common anti-pattern I see from JavaScript developers is the misuse of
Promise.reject(...)
. When usingasync/await
promise rejection is analogous to throwing an exception, which should not be used for business logic. A good rule of thumb is tothrow
orreject
only when assumptions made by your business logic have not been met, eg. null parameters and such.async/await
is just a layer on top of promises. Addingasync
to a function that doesn’t need it (e.g. it doesn’t callawait
inside) will add a wasteful promise wrapper and a next-tick operation. This is because a promise always resolves on a next-tick andasync
methods always return a promise.