GitXplorerGitXplorer
s

combine-promises

public
205 stars
5 forks
3 issues

Commits

List of commits on branch main.
Unverified
c65e4d893ba184f514f52385d8486dc36acdc9c9

improve CI

sslorber committed a year ago
Unverified
494a5bee500dfedecb26b3a656069382efef3fc5

improve CI

sslorber committed a year ago
Unverified
7ff6539a3ca7f528d195adb1b9a83ef34f9ebef0

improve CI

sslorber committed a year ago
Unverified
e474a4f93006ee665c8b66b67f523ff54bd7b3d3

improve CI

sslorber committed a year ago
Unverified
679d8bb4a574707065a5daeb206018f175b8ec08

improve CI

sslorber committed a year ago
Verified
79b569acbe9e47b3eb71bb6bc29ba51a657ef415

Merge pull request #6 from raskyer/main-1

sslorber committed a year ago

README

The README file for this repository.

Combine-Promises

NPM CI Size min Size minzip

Like Promise.all([]) but for objects.

import combinePromises from 'combine-promises';

const { user, company } = await combinePromises({
  user: fetchUser(),
  company: fetchCompany(),
});

Why:

  • Insensitive to destructuring order
  • Simpler async functional code

Features:

  • TypeScript support
  • Lightweight
  • Feature complete
  • Well-tested
  • ESM / CJS

Sponsor

ThisWeekInReact.com: the best newsletter to stay up-to-date with the React ecosystem:

ThisWeekInReact.com banner


Install

npm install combine-promises
// OR
yarn add combine-promises

TypeScript support

Good, native and strict TypeScript support:

  • Return type correctly inferred from the input object
  • All object values should be async
  • Only accept objects (reject arrays, null, undefined...)
const result: { user: User; company: Company } = await combinePromises({
  user: fetchUser(),
  company: fetchCompany(),
});

Insensitive to destructuring order

A common error with Promise.all is to have a typo in the destructuring order.

// Bad: destructuring order reversed
const [company, user] = await Promise.all([fetchUser(), fetchCompany()]);

This becomes more dangerous as size of the promises array grows.

With combinePromises, you are using explicit names instead of array indices, which makes the code more robust and not sensitive to destructuring order:

// Good: we don't care about the order anymore
const { company, user } = await combinePromises({
  user: fetchUser(),
  company: fetchCompany(),
});

Simpler async functional code

Suppose you have an object representing a friendship like {user1: "userId-1", user2: "userId-2"}, and you want to transform it to {user1: User, user2: User}.

You can easily do that:

import combinePromises from 'combine-promises';
import { mapValues } from 'lodash'; // can be replaced by vanilla ES if you prefer

const friendsIds = { user1: 'userId-1', user2: 'userId-2' };

const friends = await combinePromises(mapValues(friendsIds, fetchUserById));

Without this library: good luck to keep your code simple.

Inspirations

Name inspired by combineReducers from Redux.