1.0.10 • Published 5 years ago

attempt-async-await v1.0.10

Weekly downloads
2
License
ISC
Repository
github
Last release
5 years ago

attempt-async-await

A javascript and typescript helper that runs async await function several times with delays until it returns result or attempts ends.

Installation

npm install attempt-async-await --save

Usage

Javascript

var attempt = require('attempt-async-await');
async function methodWithError(parameter) {

    if (methodWithError.counter < 3) {
        methodWithError.counter++;
        throw new Error('Error');
    }

    return parameter + ' World!';
}

methodWithError.counter = 1;

// invokes methodWithError 5 times with delay 200ms between errors
const result = await attempt.attempt(5, 200, null, methodWithError, 'Hello');
console.log(result);

Output

Hello World!

TypeScript

import { attempt } from 'attempt-async-await';
async function methodWithError(parameter: string): Promise<string> {

    if (methodWithError.counter < 3) {
        methodWithError.counter++;
        throw new Error('Error');
    }

    return parameter + ' World!';
}

methodWithError.counter = 1;

// invokes methodWithError 5 times with delay 200ms between errors
const result: string = await attempt(5, 200, null, methodWithError, 'Hello');
console.log(result);

Output

Hello World!

Build

npm run build

Tests

npm run test

Other examples

async function methodWithError(parameter) {
    if (methodWithError.counter < 3) {
        methodWithError.counter++;
        throw new Error('Error' + methodWithError.counter);
    }

    return parameter;
}

const parameter = 'finish';

// run 50 times with delay 200ms
const result = await attempt(50, 200, (error) => {
    if (error.message === 'Error3') {
        // stop attempts
        return false;
    } else {
        // continue execution
        return true;
    }
}, methodWithError, parameter);

If the method always throw exception the result of the attempt will be the last exception.

async function methodWithError(parameter) {
    throw new Error('Error ' + parameter);
}

// the code throws Error and you should resolves that
const result = await attempt(5, 200, null, methodWithError, 'test');
1.0.10

5 years ago

1.0.9

5 years ago

1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago