Nested Promises in JavaScript
JavaScript promises?
A promise is an object which returns either a resolved value or a reason for rejection. And JavaScript Promises provide a cleaner and more intuitive way to deal with the completion (or failure) of asynchronous tasks.Creating a Promise
Constructor of the promise object takes a
callback function and it has two arguments which are also functions called resolve and reject.
resolve really means promise is fulfilled and reject means promise is not fulfilled in given constraint.
resolve really means promise is fulfilled and reject means promise is not fulfilled in given constraint.
Executing the promise


Then() is the method which get called when
the promise is resolved. Within that method there is a callback function and
because its only get executed when the promise is resolved, status can be received
back from the resolve() function.
resolve() pass the argument inside the
function(did the exam) and when the promise is fulfilled using then() it will pass
the argument inside(fromResolve) which is the same argument in resolve.
So as in the example if the student did the
exam then it would resolve it if not, it would it reject it.
Nested promises
Here in the code have separate functions with 3 promises.1st function returns a promise to do exam and within it is being directly resolved. Similarly 2nd and 3rd functions should happen one after the other.
When doExam function executes it returns a promise object.as I mentioned before it has then method which actually waits for promise to finish. And only then it would run then().and it will return the calResult function. As in the 1st function calResult and generateGrade functions will return its promises.
Multiple promises can chain together by returning another promise inside the then() method
Comments
Post a Comment