Promises Part 3

Why didn’t I think of this before? To defer the result of a Promise return another Promise. It’s so easy and removes the need for the defer API.

it('A Promise result can be deferred by returning another Promise - success case', function(){
    var p1 = new Promise(),
        p2 = new Promise(),
        p3,
        result;

    p3 = p1.then(function(){
         return p2;
    }).then(function(r){
         result = r;
    });

    p1.resolve();
    expect(p3.state).toBe('unfulfilled');
    p2.resolve('The Answer');
    expect(result).toBe('The Answer');
});

Similarly for the failure case:

it('A Promise result can be deferred by returning another Promise - failure case', function(){
    var p1 = new Promise(),
        p2 = new Promise(),
        p3,
        message,
        furtherInfo;

    p3 = p1.then(function(){
         return p2;
    }).otherwise(function(m,i){
         message = m;
         furtherInfo = i;
    });

    p1.resolve();
    expect(p3.state).toBe('unfulfilled');
    p2.reject('Bad','Promise');
    expect(message).toBe('Bad');
    expect(furtherInfo).toBe('Promise');
});

This little thing makes the Promises/A spec so powerful.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *