Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do promises work in JavaScript?

Tags:

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?

like image 639
M.K. Safi Avatar asked Aug 24 '13 18:08

M.K. Safi


People also ask

What are the 3 states of a JavaScript Promise?

A promise object has one of three states: pending: is the initial state. fulfilled: indicates that the promised operation was successful. rejected: indicates that the promised operation was unsuccessful.

How do promises work in node JS?

A Promise in Node means an action which will either be completed or rejected. In case of completion, the promise is kept and otherwise, the promise is broken. So as the word suggests either the promise is kept or it is broken. And unlike callbacks, promises can be chained.


1 Answers

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:

var promise = {   isDone: false,   doneHandler: null,   done: function(f) {     if (this.isDone) {         f();     } else {         this.doneHandler = f;     }   },   callDone: function() {     if (this.doneHandler != null) {         this.doneHandler();     } else {         this.isDone = true;     }   } }; 

You can define the action first, then trigger it:

promise.done(function(){ alert('done'); }); promise.callDone(); 

You can trigger the action first, then define it:

promise.callDone(); promise.done(function(){ alert('done'); }); 

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.

like image 61
Guffa Avatar answered Oct 26 '22 05:10

Guffa