Javascript Promises

My collected notes on the topic of Promises in Javascript.

A Promise is an object representing the eventual completion or failure of an asynchronous operation.

Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.

A promise in JavaScript is an abstraction around the idea of an asynchronous callback that supports chaining. This makes the code read to the humans like it is procedural. Do step #1 then step #2 then step #3 all while allowing the computer to handle all the asynchronicity in the all the calls.

But the most immediate benefit of promises is chaining.

Basically promises are much more composable + predictable than callbacks.

…modern functions return a promise you can attach your callbacks to instead.

Unlike “old-style”, passed-in callbacks, a promise comes with some guarantees:

  • Callbacks will never be called before the completion of the current run of the JavaScript event loop.
  • Callbacks added with then() even after the success or failure of the asynchronous operation, will be called, as above.
  • Multiple callbacks may be added by calling then() several times. Each callback is executed one after another, in the order in which they were inserted.

At their most basic, promises are a bit like event listeners except:

  • A promise can only succeed or fail once. It cannot succeed or fail twice, neither can it switch from success to failure or vice versa.
  • If a promise has succeeded or failed and you later add a success/failure callback, the correct callback will be called, even though the event took place earlier.

This is extremely useful for async success/failure, because you’re less interested in the exact time something became available, and more interested in reacting to the outcome.

var myp = new Promise(function(resolve, reject) {
  setTimeout(function(){
  	var x = 1 + 6;
  	resolve(x);
  	console.log(x);
  }, 3000)
});
myp.then(function(result) {
	return new Promise(function(resolve, reject) {
		setTimeout(function() {
			var y = result + 12;
			resolve(y);
			console.log(y);
		}, 3000);
	})
}).then(function(result2) {
	console.log(result2 + 11);
}).then(function() {
	console.log("Finished");
});

Resources