Skip to content

Instantly share code, notes, and snippets.

@karloscodes
Last active February 27, 2018 15:39
Show Gist options
  • Save karloscodes/23d96df11b6b56e92c2c2ffad90bc12c to your computer and use it in GitHub Desktop.
Save karloscodes/23d96df11b6b56e92c2c2ffad90bc12c to your computer and use it in GitHub Desktop.
Comparing promise chaining solutions. Javascript, Async, Bluebird, Callbag
const { forEach, fromIter, map, filter, pipe, interval, take, fromPromise, flatten } = require('callbag-basics');
const request = require('request-promise');
const Promise = require('bluebird');

const events = [
  { type: 'event', value: 1 },
  { type: 'event', value: 2 },
  { type: 'event', value: 3 },
  { type: 'event', value: 4 },
  { type: 'event', value: 5 },
  { type: 'event', value: 6 },
  { type: 'event', value: 7 },
  { type: 'event', value: 8 },
  { type: 'event', value: 9 }
];

const getPerson = async id => await request({ uri: `https://starwars.egghead.training/people/${id}`, json: true });


// -------------
const loadEvents = fromIter(events);
const loadPerson = map(event => fromPromise(getPerson(event.value)));
const source = pipe(loadEvents, loadPerson, flatten);
forEach(x => console.log(JSON.stringify(x.name)))(source);
// -------------

// -------------
Promise.resolve(events)
  .then(events => Promise.map(events, event => getPerson(event.value), { concurrency: 1}))
  .then(results => results.forEach(r => console.log(r.name)));
// -------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment