Promises: Leveling Up

(Psst! all the code for this post can be found here! Pass it on...)

(Psst-psst! This a continuation of a discussion about promises started in this post! Pass it on...)

Here are some useful things you can do with Promises.

How about a promise that always fails?

const failure = Promise.reject('This always fails!')

failure  
    .then(() => console.log('this function is never called'))
    .catch(error => console.log(error))
//prints This always fails!

If have a function that returns a promise, sometimes that function might need to return one that is guaranteed to fail.

Similarly, you might want a promise that is guaranteed to succeed:

const success = Promise.resolve('This always succeeds!')

success  
    .then(success => console.log(success))
    .catch(() => console.log('this function is never called'))
//prints This always succeeds!

What if we have a bunch of promises we want to wait for before we do anything? Promise.all will return a promise that only resolves when each promise in the array you give it resolves:

Promise.all([  
    $get('/firstappearance/9'),
    $get('/firstappearance/10'),
    $get('/firstappearance/11')
])
    .then(
        R.pipe(
            R.map(sidekick => ({
                name: sidekick.name,
                real_name: sidekick.real_name,
                title: sidekick.first_appearance.title,
                year: sidekick.first_appearance.year
            })),
            console.log
        ))
/*
prints:  
[
    {
        'name': 'Robin',
        'real_name': 'Damian Wayne',
        'title': 'Batman #655',
        'year': 2006
    },
    {
        'name': 'Robin',
        'real_name': 'Stephanie Brown',
        'title': 'Detective Comics #647',
        'year': 1992
    },
    {
        'name': 'Robin',
        'real_name': 'Carrie Kelly',
        'title': 'Batman: The Dark Knight Returns',
        'year': 1986
    }
]
*/

Finally, Promise.race will use the callback you give it for the first promise to resolve (from a given array):

Promise.race([  
    new Promise((resolve, reject) =>
        setTimeout(resolve, 100, "This promise wins")),
    new Promise((resolve, reject) =>
        setTimeout(resolve, 200, "This promise loses"))
])
    .then(result => console.log(result))
//prints This promise wins

Pretty good right?

Looking for a software developer?