Skip to content

Instantly share code, notes, and snippets.

@colingourlay
Last active June 15, 2019 22:42
Show Gist options
  • Save colingourlay/c304f83abebea95488760c3c44e13fd2 to your computer and use it in GitHub Desktop.
Save colingourlay/c304f83abebea95488760c3c44e13fd2 to your computer and use it in GitHub Desktop.
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
Copy link

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