JavaScript promises, mastering the asynchronous


Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

First of all, to use the Promise class, all you have to do is this:

var promise = new Promise(function(resolve, reject) {


Beware: this class is not available everywhere. If you want to use it in a browser, take a look at caniuse. If you need to use the Promise class in Internet Explorer, you should use the Q library. Q has multiple ways to create a promise, but if you want to stick with the standard way to create a promise, you should use this one:

var promise =  Q.Promise(function(resolve, reject) {


If you use AngularJS, you have to use the $q service:

var promise =  $q(function(resolve, reject) {


In many recent frameworks, any asynchronous function will return a "Promise-like" object:

// Ajax request in jQuery:
var promise = $.get('/foo/bar/common');

// Ajax request in AngularJS:
var promise = $http.get('/foo/bar/common');

// $timeout service in AngularJS
var promise = $timeout(function() {
}, 1000);
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content