JSFiddle - React, Tailwind, and code Playground
JavaScript
/**
* Run conditions in short-circuit manner. If a condition resolves to true, run trueCallback. If all conditions resolve to false, run falseCallback.
* @param trueCallback
* @param falseCallback
* @param reject Optional. If any condition is rejected, call this callback. Neither trueCallback or falseCallback will be called.
* @param conditions
*/
function promisesOr(trueCallback, falseCallback, ...args) {
let conditions;
let reject;
if (args.length === 0)
throw new Error("Expected usage is promisesOr(trueCallback, falseCallback, conditions) or promisesOr(trueCallback, falseCallback, reject, conditions)");
else if (args.length === 1) {
conditions = args[0];
} else {
reject = args[0];
conditions = args[1]
}
if (conditions.length === 0)
falseCallback();
else {
conditions.shift()().then(r => {
if (r)
trueCallback();
else
promisesOr(trueCallback, falseCallback, reject, conditions);
}).catch(reject);
}
}
function detectA() {
return new Promise(resolve => {
setTimeout(() => resolve(true), 1000);
});
}
function detectB() {
return new Promise(resolve => {
resolve(1===2);
});
}
function detectC() {
return new Promise(resolve => {
setTimeout(() => resolve(true), 1000);
});
}
promisesOr(()=>document.write("A or B or C exists."),
()=> document.write("false"),
reason=> document.write("error: "+ reason),
[detectA,detectB, detectC]);