The javascript engineers have been troubled often with the callbacks and the callback hell. The rescue are the promises: an easy and convenient way to handle the asynchronous calls.
What are the promises?
A promise is an alternative way which allows us to handle asynchronous operations in a more elegant way than callbacks
Let's assume a simple story which will help us understand this. (well OK, I know that its not the best example you've ever read)
A father asks his son to go and buy a newspaper. The father is awaiting for the newspaper and will start reading it when his son returns back. On the other hand, the father knows that his son, who loves playing out in the yard, has some possibilities to fall down and start crying. In this case he won't read his newspaper and he will have to care of his son. There are two cases in the story; the father will read the newspaper. The father won't read the newspaper.
As seen above, the function that depicts that the father is awaiting for the newspaper is in line 9. If his son won't play in the yard, then the line 10 will be executed, otherwise the line 11 will. Note that the line 11 will be executed if and only if the reject function in line 4 is invoked
Async/await
The promises were definitely a rescue of callbacks but soon the promise chain problem came in the surface. The async/await of ES7 is the new rescue :) !!Hurrah!!
The async/await is built on top of promises. The async declares an asynchronous function, whereas the await is awaiting for the result/execution of this function. We could say that the await wraps a function with a Promise. Let's re-write the simple_promise_01 with async/await.
Notice that the function buyNewspaperFunc() is the same as the previous example.
The fatherFunc() is an async function construction rather a simple function. In line 9, the code is blocking the execution and waits for the result, which in turn is assigned in variable x. What about the error handling? How can we handle the rejected promises? The try-catch statement, which we all love :) makes things more readable and maintainable.
The above example will catch the rejected promise (line 3) and will console.log the 'ERROR'.
Comments
|
AuthorI am an Angular GDE, content creator who loves sharing knowledge TagsAll Angular Angularjs General Graphql Ionic Javascript .net Nodejs Typescript |