From de77cd381bc74a53ee0f90ed9675ba1b0b200e68 Mon Sep 17 00:00:00 2001 From: joe fleming Date: Tue, 19 Feb 2019 16:37:38 -0700 Subject: [PATCH] feat: add 'exec and check' helper useful for re-executing some function if the expected result isn't found --- src/lib/exec_and_check.mjs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 src/lib/exec_and_check.mjs diff --git a/src/lib/exec_and_check.mjs b/src/lib/exec_and_check.mjs new file mode 100644 index 0000000..b89f140 --- /dev/null +++ b/src/lib/exec_and_check.mjs @@ -0,0 +1,21 @@ +export default async function execAndCheck(fn, test, onFailure = () => {}, opts = { tries: 3 }) { + let count = 0; + + const tryExec = async () => { + // exec function + await fn(); + + // check test function result (pass/fail) + const res = await test(); + if (res) return; + + // if retry limit is hit, call failure function + count += 1; + if (count >= opts.tries) return onFailure(); // eslint-disable-line consistent-return + + // retry the function and retest the results + return tryExec(); // eslint-disable-line consistent-return + }; + + return tryExec(); +}