-
-
Save 0x6a68/b64631be473c27dae0502370982c3857 to your computer and use it in GitHub Desktop.
Retrieve tuples from Promise results / async functions
This file contains hidden or 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
/** | |
* Returns a Promise which resolves with a value in form of a tuple. | |
* @param promiseFn A Promise to resolve as a tuple. | |
* @returns Promise A Promise which resolves to a tuple of [error, ...results] | |
*/ | |
export function tuple (promise) { | |
return promise | |
.then((...results) => [null, ...results]) | |
.catch(error => [error]) | |
} | |
/** | |
* Returns a function which creates a tuple-ful Promise. | |
* @param fn A function to create a tuple from. | |
* @returns A function which creates a tuple from `fn`. | |
*/ | |
export function tuplify (fn) { | |
return function tupleFn (...args) { | |
return tuple(fn(...args)) | |
} | |
} |
This file contains hidden or 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
import { tuple, tuplify } from './promise-tuple' | |
// Using tuple to pass a Promise to be resolved as a tuple. | |
async function doFetch () { | |
const [error, result] = await tuple(fetch('https://google.com')) | |
if (error) { | |
return console.log('Oh, no!', error) | |
} | |
console.log('Yey!', result) | |
} | |
// Using tuplify to retrieve tuples from async function. | |
const tupleFetch = tuplify(fetch) | |
async function doTupleFetch () { | |
const [error, result] = await tupleFetch('https://google.com') | |
if (error) { | |
return console.log('Oh, no!', error) | |
} | |
console.log('Yey!', result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment