Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Created May 2, 2024 05:02
Show Gist options
  • Save dfkaye/b964e6392529b0da5c6c80db3c332fac to your computer and use it in GitHub Desktop.
Save dfkaye/b964e6392529b0da5c6c80db3c332fac to your computer and use it in GitHub Desktop.
promise handler that returns promises as { value } or { error: { message } } structures
// 26 April 2024
// promise handler that returns promises as {value} or {error: {message}}
// structures - that is, a resolved promise with a value field, or a rejected
// promise with an error field that in turn contains a message field.
// goaded by Austin Gil's tweet 25 April 2024:
// https://twitter.com/heyAustinGil/status/1783622633000710321
// his solution, slightly modified...
/*
function IP(p) {
return p.then(r => [undefined, r], e => [e, undefined]);
}
var [e1, v1] = await IP(Promise.reject("one"));
if (e1) { console.log("first failed", e1) }
var [e2, v2] = await IP(Promise.reject(2));
if (e2) { console.log("second failed", e2) }
var [e3, v3] = await IP(Promise.resolve([,,]));
if (e3) { console.log("third failed", e3) }
console.log(v1, v2, v3)
*/
// my solution
// resolve promise or value
function P(v) {
var f = (v) => ({ value: v });
return Promise.resolve(v).then(f);
}
// reject promise or value
function R(m) {
var f = (m) => ({ error: { message: m } });
return Object(m).constructor === Promise
? m.then(f).catch(f)
: Promise.reject(m).catch(f);
}
// inline promise
function IP(p) {
return Object(p).constructor === Promise
? p.catch(R)
: P(p);
}
console.log( (await P(5)).value );
console.warn( (await R('message')).error.message );
console.warn( (await R(Promise.reject("abc"))).error.message );
console.warn( (await R(Promise.resolve("xyz"))).error.message );
var e = await IP(Promise.reject("too many notes"));
console.log( 'value' in e );
if (e.error) { console.warn(e.error.message); }
var v = await IP(Promise.resolve(42));
if (v.value) { console.log(v.value); }
var q = IP('x');
console.log( (await q).value );
console.log( (await IP('yy')).value );
console.warn( (await R("bonk")).error.message );
console.warn( (await IP( R('fail'))).error.message );
console.log( "---");
console.log( (await IP( P("ok") )).value );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment