Skip to content

Instantly share code, notes, and snippets.

@colingourlay
Last active Jun 15, 2019
Embed
What would you like to do?
The `flat` function allows you to write then-able functions without explicitly creating your own Promises, and instead receiving the promise resolution/rejection functions as a destructure-able object as a first argument.
function flat(fn) {
return function (...args) {
return new Promise((resolve, reject) => {
fn.call(this, {resolve, reject}, ...args);
});
};
}
(async function () {
const a = x => new Promise(resolve => resolve(x));
const b = flat(({resolve}, x) => resolve(x));
const results = Promise.all([a('👌'), b('💯')]);
console.log(await results);
// > ["👌", "💯"]
})();
@bevacqua

This comment has been minimized.

Copy link

@bevacqua bevacqua commented Feb 3, 2017

return function (...args) {
  return new Promise((resolve, reject) => {
    fn.call(this, {resolve, reject}, ...args);
  });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment