DEV Community

Cover image for How I use JavaScript Promises

How I use JavaScript Promises

Shubhojyoti on July 25, 2019

Originally published at Shubho.Dev Async programming in JavaScript was scary for me. The only async paradigm I was comfortable with was jQuery's $...
Collapse
 
andrevinsky profile image
Andrew Revinsky

Hi,

on your template, you seem to be enjoying the verbosity. If not, I recommend:

function sample() {
    return new Promise((rs, rj) => {
        // call rs() or rj() and bail out
        // if no need for rj(), use only rs
    });
}

and since you are using arrow functions, do you always use parentheses? This:

    (rollNumber) => {
                resolve(rollNumber);
     }

becomes..

rollNumber =>resolve(rollNumber)

Wait, what?!

This:

.then((rollNumber) => {
                resolve(rollNumber);
            })

.. easily becomes this:

.then(resolve)

Back to your promise template. Here's a much lighter version. You don't need to reject, you throw:

function sample() {
    return new Promise(rs => {
        // your stuff
    });
}

Then on this monstrosity:

rollNumberPromise
        .then((rollNumber) => {
            return get_marks_from_db(rollNumber);
        })
        .then((marks) => {
            resolve(marks);
        })
        .catch((err) => {
            reject(err);
        });

Consider changing it into:

rollNumberPromise
        .then(get_marks_from_db)
        .then(resolve)
        .catch(reject);

It also helps to familiarize with async/await constructs.

You concluded that 'Promises are difficult'. Please try to understand the main reason they exist (I am not telling you that now, sorry) - you will then see they are not so difficult at all.

Collapse
 
shubho profile image
Shubhojyoti

Thanks for reading. The verbosity was intentional. The point was to show how to use Promises while writing functions as a beginner. Using arrow functions surely uses less lines of code and I use that in my actual projects. However explaining Promises to my juniors using arrow function was always difficult. I am familiar with async/await constructs. I still prefer Promises and use it as much as possible. But my colleagues who came from Java background they preferred async/await more 😀

Collapse
 
cuitpoisson profile image
cuitpoisson

Maybe the point of the article was to show how simple it is to wrap everything in a promise, but starting with the original:

function getRollNumberFromName(studentName) {
    return new Promise(function(resolve, reject) {
        fn_to_get_roll_number_from_db(studentName)
            .then((rollNumber) => {
                resolve(rollNumber);
            })
            .catch((err) => {
                reject(err);
            });
    });
}

And combining with your suggestion (and doing the same with reject):

function getRollNumberFromName(studentName) {
    return new Promise(function(resolve, reject) {
        fn_to_get_roll_number_from_db(studentName)
            .then(resolve)
            .catch(reject);
    });
}

We can see that the then is just returning the value from the original promise and the catch is also just rejecting with the already rejected value. That means we're just returning the original promise, which can be simplified to:

function getRollNumberFromName(studentName) {
    return fn_to_get_roll_number_from_db(studentName);
}

Which is just the fn_to_get_roll_number_from_db function.

Collapse
 
jaakidup profile image
Jaaki

I'll tell you one thing, that Promise chain example you gave is one of the main reasons prefer other languages over JS. That can easy make some scary ugly monster code !

Collapse
 
mongopark profile image
Ola' John Ajiboye

This isn't really a problem with JS. Like others have shown it can be significantly simplified.

Collapse
 
jaakidup profile image
Jaaki

Sure, I must say that at least the new Async Await is cleaner, which is somthing I've actually used much more than Promises, as I spend more time in Go

Collapse
 
zeddotes profile image
zeddotes

Seems like callback hell awaiting. Why not use async/await?

Collapse
 
nadim profile image
Nadim

Thank you for your awesome post, I prefer async/await it's much more easier for me.