Back
Close

JavaScript promises, mastering the asynchronous

Magus
37.9K views

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() {
    console.log('test');
}, 1000);
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants