4 ms·
In my opinion, these are the major ones: 1. Promises are a value. They can be passed to other functions. This simplifies a lot of control flow. 2. The `.then`
by vkjv 10y ago
In my opinion, these are the major ones:
1. Promises are a value. They can be passed to other functions. This simplifies a lot of control flow.
2. The `.then` method on a promise is similar to `flatMap` in other languages / libs. The next chain will wait for any nested promises to complete. This flattens callbacks so you can see the flow instead of the pyramid of doom.
3. Native promises include a bit of sugar, such as Promise.all. You need a library to do this with callbacks.
4. Promises are the backbone of async/await. You need them to use it.
Example:
await const [a, b] = Promise.all([getA(), getB()]);
- jcheng 10y ago5. Error handling and even successful termination is very, very easy to get wrong with nested callbacks (forgetting to call a callback, or forgetting to catch unexpected exceptions and pass them to the callback, means the function never returns at best or brings down the whole process at worst). Promises make this much easier by automatically propagating errors for you down the promise chain (though you or your caller do still need to handle the error at the end of the chain).
- rictic 10y agoNit, but await is an operator, not an annotation on a statement. So that should be written as: const [a, b] = await Promise.all([getA(), getB()]);