Is it possible to configure the async.retry method to retry even upon successful queries, depending on a specific condition?

Currently, I am delving into the node.js async module and wondering if it's possible to modify the behavior of the async.retry method. Specifically, I'd like it to retry even on successful operations but halt based on a certain condition or response - for instance, in the case of an API call.

Based on the documentation, this function will keep attempting the task upon failures until it succeeds. Once it does succeed, it will only run that one time. But how can I achieve the same behavior on successful operations and have it stop under a specific condition?

const async = require('async');
const axios = require('axios');

const api = async () => {
    const uri = 'https://jsonplaceholder.typicode.com/todos/1';

    try {
        const results = await axios.get(uri);
        return results.data;
    } catch (error) {
        throw error;
    }
};

const retryPolicy = async (apiMethod) => {
    async.retry({ times: 3, interval: 200 }, apiMethod, function (err, result) {
        // should retry until the condition is met
        if (result.data.userId == 5) {
            // stop retrying
        }
    });
};

retryPolicy(api);

Answer №1

A solution is to throw a custom error if a certain condition is not met. Your code could look something like this:

const async = require('async');
const axios = require('axios');

const fetchData = async () => {
    const url = 'https://jsonplaceholder.typicode.com/todos/1';

    try {
        const response = await axios.get(url);
        if (response.data.userId != undefined && response.data.userId == 5) { // adjust the condition as needed
            return response.data;
        } else {
            throw { name: "BadDataError", message: "The received data is not valid" };
        }
    } catch (error) {
        throw error;
    }
};

Answer №2

It doesn't seem likely that this can be achieved. Check out the description provided on the async.retry documentation page:

This function attempts to execute a task successfully no more than a specific number of times before giving up and returning an error. If the task is successful, the callback function will receive the result. In case all attempts fail, the callback function will receive the error along with the result (if applicable) from the final attempt.

Alternatively, by utilizing the delay function as demonstrated in this example, you can achieve your desired outcome another way:

const async = require('async');
const axios = require('axios');

const delay = (t, val) => {
   return new Promise((resolve) => {
       setTimeout(() => { resolve(val) }, t);
   });
}

const api = async () => {
    const uri = 'https://jsonplaceholder.typicode.com/todos/1';

    try {
        const results = await axios.get(uri);
        return results.data;
    } catch (error) {
        throw error;
    }
};

const retryPolicy = async (apiMethod) => {
    const times = 3
    const interval = 200
    let data

    for (count = 0; count < 3; count++) {
        try {
            data = await apiMethod()
        catch(e) {
            console.log(e)
            await delay(interval)
            continue
        }
        if (data.userId === 5) {
            break;
        }

        await delay(interval)
    }
   
    // carry out further actions
};

retryPolicy(api);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a file with jQuery and send it to PHP

Hello everyone, I am currently in the process of developing a website that has the ability to generate an MS Excel file using jQuery and allow users to download it. My question is, how can I pass this generated file to PHP so that it can be sent as an atta ...

Encountering issues with retrieving application setting variables from Azure App Service in a ReactJS TypeScript application resulting in '

My dilemma lies in my app setup which involves a Node.js runtime stack serving a ReactJs Typescript application. I have set some API URLs in the application settings, and attempted to access them in ReactJs components using process.env.REACT_APP_URL, only ...

Mastering the Vue 3 Composition API: A guide to efficiently utilizing it across multiple Vue instances spread across different files

tl;dr What is the best way to import Vue3 in a base Javascript file and then utilize Vue's composition API in subsequent standalone files that will be loaded after the base file? I incorporate Vue to improve user interactions on specific pages like t ...

Using the feColorMatrix SVG filter in CSS versus applying it in JavaScript yields varied outcomes

If we want to apply an SVG filter on a canvas element, there are different ways to achieve this. According to this resource, we can apply a SVG filter to the CanvasRenderingContext2D in javascript using the following code snippet: ctx.filter = "url(#b ...

Ways to dynamically toggle visibility and hide elements by clicking outside the specified div

I have a div that, when clicked, displays a contact us form. This form toggles between being visible and hidden. How can I make it hide when clicked on another part of the document? Here is the code: function showContactForm(){ var formWidth = &apos ...

What is the best way to locate the position of a different element within ReactJS?

Within my parent element, I have two child elements. The second child has the capability to be dragged into the first child. Upon successful drag and drop into the first child, a callback function will be triggered. What is the best way for me to determi ...

Animating the opacity of elements using jQuery and CSS

Trying to put together a fading slideshow with five slides that will loop back to the beginning. My code seems like it should do the trick, but there's something not quite right. <script type="text/javascript"> $(document).ready(function( ...

Is it advisable to employ Promise.all in this scenario? Elaborate in the explanation

When working with functions, it is important to validate data before processing and handling logic. Sometimes we need to verify if data exists in the database or not, and if it doesn't, return a 404 error immediately and stop the function. In some cas ...

Passport JWT operates seamlessly with an empty payload

I have set up a strategy for JWT: const jwtStrategyOptions = { jwtFromRequest: ExtractJwt.fromHeader('x-access-token'), secretOrKey: 'publicKey', } passport.use( new JwtStrategy( jwtStrategyOptions, (payload, done) => ...

Attempting to initialize 'awsmobile init' for a web React project is proving to be unsuccessful

Following the AWS Documentation instructions, I created a hello-world react app. However, when attempting to run the "awsmobile init" command in the app root folder, I encountered an error stating 'Unexpected token function'. My current node ver ...

Verify the functionality of a specific method invoked within another method through unit testing

I currently have a method in my Angular application that is triggered upon clicking. Inside this method, I pass a value to another private method. .ts file public onViewItem(item: Results): void { const ids = [item.data['id']]; this.anot ...

Choosing the Right SQLite Library for Node.js

Currently, I am in the process of developing an application using node.js. For the embedded database functionality, I have decided to use SQLite. After exploring various npm modules for SQLite, I came across a few options: https://github.com/grumdrig/nod ...

Utilize AngularJS to Capitalize the First Letter and the Letter Following a Dot (.)

I am seeking a solution to capitalize the first letter in a given string, like so: sumo => Sumo Additionally, I need to capitalize strings in the following format: Dr.ravi kumar => Dr.Ravi kumar Although I have implemented an Angular filter that ...

Utilizing Node.js child_process.fork() for multi-core processing with CPU affinity

I am working on an application that performs long-executing processes. In order to optimize its speed, I have implemented a simple data sharding technique and would like to run multiple instances of the application in parallel using .fork(). Currently, I ...

The debate between client-side and server-side video encoding

My knowledge on this topic is quite limited and my Google search didn't provide any clear answers. While reading through this article, the author mentions: In most video workflows, there is usually a transcoding server or serverless cloud function ...

The value of Yargs.argv is consistently displayed as [object Object]

In my Ubuntu 16.04 environment, I enrolled in a node.js course on Udemy. Following the instructor's guidance, I initially used the exact version mentioned and later updated to the latest version (11.0.0). Surprisingly, both versions yielded the same o ...

``There is an issue that arises when trying to establish a one-to-many relationship

I encountered an issue while creating a CRUD system that involves a relation between two collections. I'm facing difficulty in pushing data from the first collection to the second collection. Below is the code snippet: Schema const CourseSchema = new ...

Steps for creating new users using a post request

I've been working on developing a chat application using react-chat-engine, and everything is running smoothly except for one issue - I'm struggling to figure out how to send a post request to create new users. Below is the code snippet I'v ...

Troubleshooting directive not functioning properly with AngularJS ng-click

My HTML img tag is not responding to ng-click when clicked. I'm puzzled by this issue occurring in masonryPictureView.html Main page - home.html <ng-masonry> <ng-picture ng-items="projectdescription.pictures"></ng-picture> </n ...

Ensure that the input field consistently shows numbers with exactly two decimal places

Below is an input field that I want to always display the input value with 2 decimal places. For example, if I input 1, it should show as 1.00 in the input field. How can this be achieved using formControl since ngModel is not being used? Thank you. I att ...