Skip to content

Instantly share code, notes, and snippets.

@noahlt
Created April 1, 2019 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noahlt/d52098e66ad86c473c2957c38a0fbb79 to your computer and use it in GitHub Desktop.
Save noahlt/d52098e66ad86c473c2957c38a0fbb79 to your computer and use it in GitHub Desktop.
Iteration

Iteration with break:

var attempt = 1;
while (true) {
    var [succeeded, error] = await f()
        .then(() => [true])
        .catch(error => [false, error]);

    attempt++;
    if (succeeded || attempt > maxAttempts)
        break;

    console.log(`  RETRY(${attempt}/${maxAttempts}): ${title}`);
}

GOTO:

retryTest:
var [succeeded, error] = await f()
    .then(() => [true])
    .catch(error => [false, error]);

if (error && attempt < maxAttempts) {
    attempt++;
    console.log(`  RETRY(${attempt}/${maxAttempts}): ${title}`);
    goto retryTest;
}

const tryTest = (attempt) => {
    const [succeeded, error] = await f()
        .then(() => [true])
        .catch(error => [false, error]);

    if (error && attempt < maxAttempts) {
        console.log(`  RETRY(${attempt}/${maxAttempts}): ${title}`);
        return tryTest(attempt + 1);
    }
    return [succeeded, error];
};
tryTest(1);

Recursion with Y combinator:

const [succeeded, error] = Y((recurse, attempt = 1) => {
    const [succeeded, error] = await f()
        .then(() => [true])
        .catch(error => [false, error]);

    if (error && attempt < maxAttempts) {
        console.log(`  RETRY(${attempt}/${maxAttempts}): ${title}`);
        return recurse(attempt + 1);
    }
    return [succeeded, error];
})();

With function keyword:

const [succeeded, error] = runWithRetries({attempt: 1, maxAttempts});
function runWithRetries(attempt) {
    const [succeeded, error] = await f()
        .then(() => [true])
        .catch(error => [false, error]);

    if (error && attempt < maxAttempts) {
        console.log(`  RETRY(${attempt}/${maxAttempts}): ${title}`);
        return runTestWithRetries({attempt: attempt + 1, maxAttempts});
    }
    return [succeeded, error];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment