Skip to content

Instantly share code, notes, and snippets.

@fnky
Last active December 18, 2023 19:54
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save fnky/0a6cd5f39a7ad0ace79a7a4f5c999691 to your computer and use it in GitHub Desktop.
Save fnky/0a6cd5f39a7ad0ace79a7a4f5c999691 to your computer and use it in GitHub Desktop.
Retrieve tuples from Promise results / async functions
/**
* 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))
}
}
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