Skip to content
Resolves a promise with [response, error] instead of using a try/catch block πŸ₯ž
JavaScript
Branch: master
Clone or download
Latest commit b4ca711 Apr 22, 2018

Files

Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.gitignore Initial commit Apr 22, 2018
LICENSE Initial commit Apr 22, 2018
README.md Add example in header Apr 22, 2018
index.js Package init Apr 22, 2018
package.json Package init Apr 22, 2018

README.md

πŸ₯ž promise.flatten

Resolves a promise with [response, error] instead of using a try/catch block

npm install promise.flatten

How to use

import promiseFlatten from 'promise.flatten';

const [response, error] = await promiseFlatten(fetch('https://google.com/'));

Why?

With async and await now we can have our asynchronous code cake and eat it too. But as complexity grows we can still find ourselves in try/catch hell:

  try {
    await workItHarder();
  } catch (e) {
    return await makeItBetter();
  }

  doIt.makeUs(['harder', 'better', 'faster', 'stronger']);

  try {
    await everAfterWork.isOver();
  } catch(e) {
    console.log('enough of this');
  }

We find ourselves with a lot of cruft. Maybe we're doing something clever and don't care about the error. Here's what this looks like:

import promiseFlatten from 'promise.flatten';

const [response, error] = await promiseFlatten(fetch('https://google.com/'));

// Fun with errors
const [, error] = await promiseFlatten(fireAndForget());

// Fughettaboutit
const [response] = await promiseFlatten(feedMeResponses());
You can’t perform that action at this time.