Playing with promises

I like promises in JavaScript. I like async/await too.

I am by no means an expert in either of these topics, but importantly, I know enough to be dangerous. I thought I'd write this article to show some of the learnings I've found useful when working with Promises. This article will serve as my "thoughtpad" where I will add all of the stuff I've learnt about Promises (and sometimes Promises with async / wait).

Waiting for multiple XHR requests to resolve (using superagent):

Recently, I worked on a multi-step form that required different form sections to be posted to different API endpoints. Luckily Promise.all was there for me.

I use the superagent library in my examples, but you could do this just as well with the native fetch too.

Note: I pass a mapped version of the promises array to Promise.all in order to catch any errors from rejected promises and pass them on to the chained .then. If we don't do this, then the rejected promises will stop the flow of execution, and really we want to just pass the original requests / responses of the rejected promises on along with the requests and responses of the resolved promises to the next .then so we can treat them all equally.

import request from "superagent";

const data = [
  {
    name: "blah",
    postTo: "/existent-endpoint"
  },
  {
    name: "boo",
    postTo: "/non-existent-endpoint"
  }
];

const promises = data.map(d => request("POST", d.postTo).catch(e => e));

Promise.all(
  promises
).then(responses => {
  // Collect all promise rejections / resolutions
  console.log(responses);
  // => [Response, Error]
});

CodeSandbox: https://codesandbox.io/s/xrp62z121z

Basic async / await with Promise example

Awaiting the result of a method returning a Promise is pretty easy. Be sure to .catch any promise rejections whilst calling await on the method returning the Promise!

import "regenerator-runtime/runtime";

let someCondition = false;

const someMethod = () =>
  new Promise((resolve, reject) => {
    if (someCondition) {
      resolve("some value");
    } else {
      reject(new Error("Some issue with your code"));
    }
  });

const asyncFunction = async () => {
  // Wait for the promise to resolve it's value.
  const falsyResult = await someMethod().catch(e => e.message);
  console.log(falsyResult);

  someCondition = true;

  const truthyResult = await someMethod();
  console.log(truthyResult);
};

asyncFunction();

CodeSandbox: https://codesandbox.io/s/rwmwnoop5o

About

⚡ I like to code, simple as that.
🎉 React, Node and Ruby etc.
🧸️ Toying with TypeScript

Elsewhere