Promises in Javascript
Promises are used in javascript to perform any asynchronous operation. Its one of the solution for the callback hell. When multiple callback would create callback hell which will lead to unmanaged code.
A promise is something like promising that the task would be completed in near future either successfully or return an error.
The syntax of the promise looks like as below.
Here the promise constructor takes a single argument which is a callback function. The callback function takes two arguments. First argument is resolve and the second argument is reject. If the task is completed successfully then we pass the result in resolve function. If the task fails then call the reject function.
Let's see an example for the promise
Output:
End of the program. 6 is an even number.
In the above program we have a function named checkEven which gets a number as an argument. This function would return a promise as response. If the number provided is an even number then resolve function is called with a message that '6 is an even number'. If the number is an odd number, say suppose its number 7 then it would call the reject function with an error message "Not an even number". In the above code when resolve is called, the callback function in the then block gets called which get the parameter returned by the resolve function. If the reject function is called then the catch block will be executed with the parameter returned by reject function.
If we note the above output, the line "End of the program" get printed first even though its present at the last line of the program. This clearly denotes that promise is an asynchronous function and javascript doesn't wait for it to execute the next line.