Simplify dealing with promises for async-heavy situations
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.

Magic Promises status

Syntax sugar for dealing with promises in a much simpler way for async-heavy workflows:

npm install magic-promises

Builds the promise chain internally, so your code can be used like you would do with sync strings, arrays, etc:

// With a bit of magic()
const value = await magic(data).map(op1).filter(op2).map(op3);

// NATIVE; the pure-javascript way of dealing with the same is a lot longer
const value = await Promise.all( => files.filter(op2)).then(files => Promise.all(;

// NATIVE; even when we try to make it more readable it is still longer:
let value = await Promise.all(;
value = value.filter(op2);
value = await Promise.all(;


The coolest bit is that there is no API. You can call the methods, properties, etc of the value that you pass to magic():

const value = await magic(3.1).toFixed(1).split('.').map(n => n * 2).join('.');
// 6.2 (string)


Note: all these must be run in an async context. I am using the great libraries mz/fs and got.

This library is specially useful if we want to do things like fetching urls, mapping their arrays, working with strings, etc. For instance, let's read all the files in the current directory:

// You can apply `.map()` straight to the output of magic()
const files = await magic(readdir(__dirname)).map(file => readFile(file, 'utf-8'));

// NATIVE; this is how you'd have to do with vanilla JS
const files = await readdir(__dirname).then(files => => readFile(file, 'utf-8')));

// PRO; using my library `fs-array`, based on magic-promises, it gets better:
const files = await dir(__dirname).map(read);

Retrieve a bunch of websites with valid responses

// Retrieve the content of several pages
const urls = ['', '', ''];
const websites = await magic(urls)
  .map(url => got(url))  // Fetch the URLs in parallel like Promise.all()
  .map(res => res.body)  // Retrieve the actual bodies
  .filter(Boolean);      // Only those bodies with content

// NATIVE; How to do this with traditional Promises + arrays
const urls = ['', '', ''];
const responses = await Promise.all( => got(url))); // Fetch the URLs in parallel
const websites = responses
  .map(res => res.body)     // Retrieve the actual bodies
  .filter(Boolean);         // Only those bodies with content

Works with any value that a promise can resolve to:

// Get and parse a CSV file. Promise => text => array => number
const sum = await magic(got(''))
  .map(line => line.split('\t').shift())
  .map(num => parseFloat(num, 10))
  .reduce((total, num) => total + num, 0);


Libraries based on this: