Javascript Promises

Eric Sanchirico
2 min readDec 16, 2020

--

Promises, more than anything else, I have found very hard to fully grasp when first learning Javascript. The difficulty I had was mostly with the .catch() and the .done() parts of a promise chain. The expected usage of Promise.all is also confusing. Promises, when fully understood, are universally preferred to async functions, as the next part of the chain only starts when the previous part is resolved.

When starting a Promise chain, you can begin by assigning a function returning a promise to a variable, then typing that variable with a .then after it, passing in what that function resolved to. This is the alternative to what is referred to as “callback hell”, which looks like a series of nested callback functions. That was how async code had to be written in Javascript before promises were introduced. With promises, you can simply chain the stages together with .then and .catch. .catch is actually short for .then(null, argument), just as you would write a callback checking for an error being throw. The .catch syntax make it much simpler to write, and greatly improves legibility. Another useful thing to note is that .catch can be chained as well, to take specific steps if an error happens, which — needless to say — improves server uptime and saves you from having to restart a server every time a caught error occurs, as the program can deal with it as it happens in the way you specified.

More complexly, Promise.all allows you to invoke itself on an array of async functions and only move on to the provided .then statement after all of the functions in the array have resolved. This is incredibly useful for when you need multiple steps to complete in between a previous step and moving on to the next step. An example of this is written below:

Promise.all([promise1(), promise2(), customFunction()].then (function (inp1, inp2, inp3) => {
console.log(inp1.toString() + inp2.toSring() + inp3.toString()]);

The last major thing to know is that Promise. race does the opposite in Promise.all, in the sense that it will continue its chain only passing in the first resolved promise’s resolved value. This is useful for if trying to reach multiple servers that would return the same response, for purposes of redundancy.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Eric Sanchirico
Eric Sanchirico

Responses (1)

Write a response