Should I read this?
which means, the flow of the program is determined by events such as user actions (mouse clicks, key presses) or messages from other programs/threads.
Here’s a simple illustration of how a callback way works. #Main script wants to execute #Function_B after #Function_A finish execution. It’s important to keep in mind that #Function_A has nothing to do with the logic of #Function_B.
#Function_A is now the parent of #Function_B and responsible for calling it at the correct time.
But things become really complicated when we need to implement multiple asynchronous operations which depend on each other. example:
Now, let’s implement this logic using classical callbacks way:
Isn’t it annoying to have nested code blocks like these? Is it readable?
Promises are the way of implementing asynchronous logic without the need of passing callbacks as arguments.
Following is a simple illustration of how things work using Promises.
- #Main script calls #Function_A
- #Function_A executes and returns a promise
- #Main script holds that promise and wait for #Function_A to trigger a success/failure signal
- #Main script calls #Function_B explicitly
Here’s how the skeleton of an async operation using promises should look like:
This is beautiful because now each ASYNC operation is encapsulated and has nothing to do with any other operation.
Let’s have a look of how our very first example should look like:
Now code looks much cleaner, readable, self descriptive, modularized (for unit testing and documentation).
It’s important to note that the .then() result is implicitly a promise. so, you can chain your operations with multiple .then()s
No, there’s a bunch of other handy features that promises do for you as well
- If -for example- we want to execute some logic after multiple promises get resolved. then we can use .all()
- If we need to execute some logic after either the promise get resolved or rejected, then we can use .finally()
- If we need to send notifications from inside the ASYNC operation to whoever has the promise, then we can use .notify()
I hope I’ve convinced you to start thinking about promises seriously. And if you already use promises I hope that you learned something new about it.
Please feel free to give your feedback and start discussions … I don’t bite!