According to Wikipedia:
A callback, also known as a “call-after” function, is any executable code that is passed as an argument to other code that is expected to call back (execute) the argument at a given time.
This issue can be solved using callbacks. The only change in function will be one extra parameter called callback. In our case updateItem is a function which accepts item object and a callback as a parameter and to return value from this function we use the parameter callback. One thing to note over here is that callback is not a predefined keyword, one can use of his own choice.
One important thing to see here is the way we are calling this function. We are expecting a callback function in return which is in our case (err, data). This part will only execute after the completion of called function.
Callbacks is really helpful if you have one or two async operation. But if you are dealing with n number of async operations, where n is too large, and want them all to run in sequence then doing that using callback will turn to hell, also called callback hell. Because of this promise came into place.
Promises is another approach for dealing with async. This is very helpful in setting up a sequence of async operations. It is powerful enough to handle any number of async operations. The above example (callback-example.js) can be done using promise in below mentioned way.
A promise object is created using new keyword followed by constructor Promise. This constructor takes function as an argument and this function takes two function as a parameter. This might be little confusing but lets understand that through our example.
In above example function updateItem() returns a promise object ( new Promise() ) which takes an argument function (resolve, reject) also called as executor function. Here (resolve, reject) is a function with two parameters resolve and reject where resolve and reject is itself a function.
Use resolve when you want to return the value after completion and reject when an error occurred.
Below is another example of promises used to run function in series.
Lets see how this works. Using the same example shown in promise, we have a function called updateItem which return a promise. So in order to wait for this function to resolve we can write either then function (which is promise chaining) or we can use await keyword.
The only catch here is you can use await only inside a async function.