nodejs: callback vs promise
Consider the code snippet below:
The second statement will not wait for the first one to complete, hence result in
true in the second statement.
When it comes to dealing with asynchronous in nodejs, we usually come down to 2 most popular options: callback and promise.
Callback is widely used but when we need 3 or more operations going in sequence, things are going to get ugly. Consider the following code snippet.
That is just one function with callback. Imagine this with 4 levels of callback. Welcome to CALLBACK HELL!!
What is a promise?
The core idea behind promises is that a promise represents the result of an asynchronous operation. A promise is in one of three different states:
- pending - The initial state of a promise.
- fulfilled - The state of a promise representing a successful operation.
- rejected - The state of a promise representing a failed operation.
Once a promise is fulfilled or rejected, it is immutable (i.e. it can never change again).
The most complete library for promise on Nodejs is