A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. There are two ways in which the callback may be called: synchronous and asynchronous. It is the most fundamental async pattern in Javascript.
For example:
Everything works perfectly during testing. People start booking travel packages on your website, and everyone is happy with your work. Suddenly, one day, you get a call from your boss regarding a major issue. A customer booked a package and received four identical confirmation emails for one booking.
You start debugging the issue. You review the part of the code that sends the confirmation email, and everything seems correct. You then investigate further and find that the createBooking() utility from the third-party library called your callback function four times, resulting in four confirmation emails being sent.
You contact the third-party library’s support team and explain the situation. They tell you they have never encountered this issue before but will prioritize it and get back to you. After a day, they call you back with their findings. They discovered that an experimental piece of code, which was not supposed to go live, had caused the createBooking() function to call the callback multiple times.
The issue was on their side, and they assured you that it has been fixed. They apologized for the trouble and confirmed that the problem would not occur again.
To prevent any unwanted issue like that after some seeking for a solution, you implement a simple if statement like the following, which the team seems happy with:
Once a Promise is resolved (successfully completed), it stays that way forever — it becomes an immutable value at that point and can then be observed as many times as necessary. That means a resolved promise, its resolved value can be accessed or used multiple times in your code without affecting its state. This allows you to handle the result of the asynchronous operation in various parts of your application without worrying about the Promise changing or being re-evaluated.
Promises are a solution for the inversion of control issues that occur in callback-only code. Callbacks represent an inversion of control. So inverting the callback pattern is actually an inversion of inversion, or an uninversion of control. Restoring control back to the calling code where we wanted it to be in the first place.
References
You Don’t Know JS: Async & Performance by Kyle Simpson
SOCIAL SHARE CARD GENERATOR