JavaScript Promise API

Tuesday, September 29, 2015

Yesterday's post looked at chaining promises. Now, let's take a closer  look at the API available for promises.

A Promise in JavaScript offers a few static methods you can use as convenience methods. For example, when you need to return a promise to a caller but you already have a value ready, the resolve method is handy.

let doAsyncWork = function () { 
    // note: no async work to perform 
    return Promise.resolve(10); 
}; 

doAsyncWork().then(result => { 
    expect(result).toBe(10); 
    done(); 
});

Likewise, the reject method will deliver a ready result to an error handler.

let doAsyncWork = function () {
    return Promise.reject("error!");
};

doAsyncWork().then(() => { }, message => {
    expect(message).toBe("error!");
    done();
});

The race method will combine multiple promises into a single promise. The single promise will resolve when the first of the multiple promises resolves. It’s a race to see who finishes first!

let slowExecutor = function (resolve, reject) {
    setTimeout(() => {
        resolve(9);
    }, 250);
};

let fastExecutor = function (resolve, reject) {
    setTimeout(() => {
        resolve(6);
    }, 100);
};

let p1 = new Promise(slowExecutor);
let p2 = new Promise(fastExecutor);

let p3 = Promise.race([p1, p2]);

p3.then(result => {
    expect(result).toBe(6);
    done();
});

In contrast to race, the all method will combine multiple promises into a single promise, and the single promise will resolve when all of the multiple promises resolve.

let slowExecutor = function (resolve, reject) {
    setTimeout(() => {
        resolve(9);
    }, 250);
};

let fastExecutor = function (resolve, reject) {
    setTimeout(() => {
        resolve(6);
    }, 100);
};

let p1 = new Promise(slowExecutor);
let p2 = new Promise(fastExecutor);

let p3 = Promise.all([p1, p2]);

p3.then(result => {
    expect(result[0]).toBe(9);
    expect(result[1]).toBe(6);
    done();
});

The results are delivered in the same order as the promises that produce each result appear in the array parameter to all.

Of course, not all promises resolve successfully, so the next post in this series will look at error handling with promises.


Comments
Comments are closed.

My Pluralsight Courses

K.Scott Allen OdeToCode by K. Scott Allen
What JavaScript Developers Should Know About ECMAScript 2015
The Podcast!