DEV Community

Cover image for Explain the synchronous, callback, and async-await (promises) approach like I am 10πŸ§’
Pankaj Tanwar
Pankaj Tanwar

Posted on • Updated on • Originally published at blog.pankajtanwar.in

Explain the synchronous, callback, and async-await (promises) approach like I am 10πŸ§’

  1. My friend was moving to Surat, invited me to a party and some shopping. We went to a restaurant. It was Sunday so the restaurant was full. They noted down our names, gave us a token number, and asked us to waitπŸ₯Ί

  2. It was taking so much time so decided to try some other restaurant. Again, no table available BUT their approach was different. They took our contact no and asked to do our shopping work and when a table was available, they would give us a call. A win-win for both.

  3. But soon, we started getting offer discount messages from the restaurant. Oops!!! The next time, we clearly denied to give them our contact no, so they gave us a buzzer which will ring when a table is empty and told us to go shopping. They have nothing from us now, it's up to us that we want to go or not when the buzzer rings.

1 - Synchronous ( Blocking approach ) - Not efficient
2 - Giving contact no means leaving a callback, non-blocking but not that efficient as no control over callback (SPAM MSGS), callback hell (nested callbacks)
3 - async-await (wrapped in promise) - asynchronous, non-blocking, easy and clean, No callback only two args - resolve and reject, efficient but messy error handling

Top comments (5)

Collapse
 
idanarye profile image
Idan Arye

Did you ever registered a callback and had it invoked with spam parameters?

Collapse
 
pankajtanwarbanna profile image
Pankaj Tanwar

Didn't understand πŸ€”πŸ€”

Collapse
 
idanarye profile image
Idan Arye

The in your allegory, the problem with the callback approach was that once the restaurant had your number, they could send you spam messages. But there is no parallel to that in actual programming - when you register a callback, no one will send spam to it.

Thread Thread
 
pankajtanwarbanna profile image
Pankaj Tanwar

Yeah. My intention here was to show that we have no control over callback. Not saying you will get spam with callback. SPAM MEANS "NO CONTROL OVER CALLBACK"

Thread Thread
 
idanarye profile image
Idan Arye

Is this an actual problem? The callbacks framework is no a potentially malicious agent that just waits for you to give it a callback so it could abuse it. If it wanted to cause damage, it could just use the fact that it is allowed to run code and even perform IOs. I've never seen a framework that does weird stuff with the callback - you can usually trust it to only run the callback once when the promise is ready.