There is a lot of material online about these and I would try to keep it short and sweet to explain what is my current understanding of these.
Promises are syntax to implement callbacks, so lets get rid of callback from the proportions.
Now we are left with Promises vs EventEmitters. Internally or performance wise all are quite similar.
So based on coding practices these are my observations:
Promise are good abstraction of asynchronous commands which will happen in given amount of time. Making a db query is a promise, making a rest cal is a promise. Your code needs to wait for promise to be fulfilled. Lets give it an analogy, a cab driver promises to come to pick you up at 6AM and when he fulfills the promise, you promise him to sit in the cab and reach office. I know analogy is little lame, but hope it explains the idea.
EventEmitters are used for truely async events, like someone clicked on a particular button on a page, or while operating on a command you detected something which is not in scope of current command so you fire and forget. Its listener responsibility to act on it. Not yours.
Going back to real work example suppose at 5.55 AM your friend comes to pick you up then that's an event. Something which is not expected.
I hope I explained my understanding of these two mechanism to achieve asynchronous behavior in Nodejs.
Promises are syntax to implement callbacks, so lets get rid of callback from the proportions.
Now we are left with Promises vs EventEmitters. Internally or performance wise all are quite similar.
So based on coding practices these are my observations:
Promise:
Promise are good abstraction of asynchronous commands which will happen in given amount of time. Making a db query is a promise, making a rest cal is a promise. Your code needs to wait for promise to be fulfilled. Lets give it an analogy, a cab driver promises to come to pick you up at 6AM and when he fulfills the promise, you promise him to sit in the cab and reach office. I know analogy is little lame, but hope it explains the idea.
EventEmitters:
EventEmitters are used for truely async events, like someone clicked on a particular button on a page, or while operating on a command you detected something which is not in scope of current command so you fire and forget. Its listener responsibility to act on it. Not yours.
Going back to real work example suppose at 5.55 AM your friend comes to pick you up then that's an event. Something which is not expected.
I hope I explained my understanding of these two mechanism to achieve asynchronous behavior in Nodejs.
No comments:
Post a Comment