View Single Post
Kalnos
Banned
(07-31-2017, 12:03 AM)
Kalnos's Avatar

Originally Posted by Kieli

I'm looking at promises, and I do not see their purpose at all. Like, asynchronous callbacks are much easier to use and understand. What the hell are "thens" and "catches"? Is JS promise trying to do a poor man's version of try-catch?

They're chainable, with async/await they let your code read like it's synchronous, they improve readability a fuck ton, you can bubble up the error handling, utility like Promise.all(). There are very few reasons to use a callback... and even when people do they wrap it in a promise in my experience.

To quote a stackoverflow post, would you rather deal with:

Code:

api(function(result){
    api2(function(result2){
        api3(function(result3){
             // do work
        });
    });
});
that or:

Code:

api().then(function(result){
    return api2();
}).then(function(result2){
    return api3();
}).then(function(result3){
     // do work
});
this?

How about with async/await?

Code:

const result = await api();
const result2 = await api2();
const result3 = await api3();
Since none of them depend on one another you could even run all 3 simuiltaneously using Promise.all if you wanted:

Code:

const results = await Promise.all([api(), api2(), api3()]);