Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add asyncRetry #38

Merged
merged 4 commits into from
Jun 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Node.js: 8.x-22.x
* [Installation](#installation)
* [Generate timestamp or random digits](#generate-timestamp-or-random-digits)
* [Generate current date and time](#generate-current-date-and-time)
* [Async retry](#async-retry)
* [Send GET, POST and other requests](#send-get-post-and-other-requests)
* [Read directories](#read-directories)
* [Contributing](#contributing)
Expand Down Expand Up @@ -68,6 +69,18 @@ console.log(process.env.DATETIME_PLUS_SECONDS); // '2024-03-14T00:14:26'
console.log(process.env.DATETIME_MINUS_HOURS); // '2024-03-13T23:14:25'
```

## Async retry
Execute a provided function once per a provided amount of milliseconds until this function will return a truthy value or the amount of provided attempts will be exceeded:
```
const { asyncRetry } = require('js-automation-tools');

const myFunction = async function () {
return await getSomeData();
}

const result = await asyncRetry(myFunction, 5, 2000) // { data: 'Some data' }
```

## Send GET, POST and other requests
Send request to any URL and get response - `sendRequest` function accepts 5
arguments:
Expand Down
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
const readDirectories = require('./utils/read-directories.js');
const stamp = require('./utils/stamp.js');
const dateTime = require('./utils/date-time.js');
const asyncRetry = require('./utils/async-retry.js');
const sendRequest = require('./utils/send-request.js');

module.exports = {
readDirectories: readDirectories,
stamp: stamp,
dateTime: dateTime,
asyncRetry: asyncRetry,
sendRequest: sendRequest,
createRequest: sendRequest
};
41 changes: 41 additions & 0 deletions utils/async-retry.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'use strict';

// #############################################################################

const _attemptsDefault = 10;
const _waitTimeDefault = 1000;

/**
* Executes a provided function once per a provided amount of milliseconds
* until this function will return a truthy value or the amount of provided attempts will be exceeded
* @param {Function} func function to execute (if successful - should return a truthy value)
* @param {Number} attempts number of attempts to retry (default value: 10)
* @param {Number} waitTime time to wait between retries (in milliseconds, default value: 1000)
* @returns {Promise} response of a function that was provided for execution
*/
async function asyncRetry (
func,
attempts = _attemptsDefault,
waitTime = _waitTimeDefault
) {
const result = new Promise((resolve, reject) => {
let iteration = 0;
const intervalId = setInterval(async () => {
console.info(`Attempt: ${iteration}`);
const res = await func();

if (res) {
clearInterval(intervalId);
return resolve(res);
} else if (iteration < attempts) {
iteration++;
} else {
return reject(new Error(`Failed to succeed in ${iteration} attempts`));
}
}, waitTime)
});

return result;
}

module.exports = asyncRetry;
Loading