I think to start, callbacks would make sense to see how it’s improved with promises and made our life easier.
Function passed inside another function as an argument, that is then called in that function to perform a task.
This snippet would return this:
This is because the setTimeout is set up to wait for 2 seconds so the threat of execution will continue, and then come back to it. This method was good until you needed to make multiple calls, and to do so you’d have to nest the functions to get the desired behaviour. This would cause end up in what was referred to as Callback Hell or Callback Pyramid of Doom.
The MDN docs define a Promise as an object that represents the eventual completion or failure of an asynchronous operation.
A promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.
Why use them?
Using promises will guarantee you some outcomes that you wouldn’t get from callbacks such as:
- If the callback is added with a
.then()it will never be invoked before the current event loop run has been completed.
- The callbacks will be invoked even if they were added after the asynchronous operation that the promise represents has succeeded or failed.
- You can add multiple callbacks just by calling
.then()several times. They will be invoked one after another, in the order in which you placed them in the code block.
- Chaining, which is worth getting into more detail.