Last active
June 15, 2019 22:42
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function flat(fn) { | |
return function (...args) { | |
return new Promise((resolve, reject) => { | |
fn.call(this, {resolve, reject}, ...args); | |
}); | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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
commented
Feb 3, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment