I just implemented my first function that returns a promise based on another promise in AngularJS, and it worked. But before I decided to just do it, I spent 2 hours reading and trying to understand the concepts behind promises. I thought if I could write a simple piece of code that simulated how promises worked, I would then be able to conceptually understand it instead of being able to use it without really knowing how it works. I couldn't write that code.
So, could someone please illustrate in vanilla JavaScript how promises work?
For the simplicity to understand about the promises in Javascript. You can refer below example. Just copy paste in a new php/html file and run.
Probably the simplest example of promises usage looks like that:
That's basic of basics. Having it, you can experiment with rejects:
As we can see, in case of failure error function is fired (which is always the second argument of
then
) and then next function in chain is fired with no given argument.For advanced knowledge I invite you here.
A promise is basically an object with two methods. One method is for defining what to do, and one is for telling when to do it. It has to be possible to call the two methods in any order, so the object needs to keep track of which one has been called:
You can define the action first, then trigger it:
You can trigger the action first, then define it:
Demo: http://jsfiddle.net/EvN9P/
When you use a promise in an asynchronous function, the function creates the empty promise, keeps a reference to it, and also returns the reference. The code that handles the asynchronous response will trigger the action in the promise, and the code calling the asynchronous function will define the action.
As either of those can happen in any order, the code calling the asynchronous function can hang on to the promise and define the action any time it wants.