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

Determining the status of form inputs with Node.js

If I want to check if an input, such as name, is set in a form using PHP, I can use the following code: if (isset($_POST['name']) { echo("type in name"); # or something } Can I achieve the same functionality in Node.js by doing the followin ...

React's setState is not reflecting the changes made to the reduced array

I am currently working on a custom component that consists of two select lists with buttons to move options from the available list to the selected list. The issue I am facing is that even though the elements are successfully added to the target list, they ...

"Trouble connecting Sequelize associations with API routes, resulting in unsuccessful retrieval of data from the database

I am currently navigating the complexities of sequelize and express, facing challenges with database associations and data retrieval. My project involves a boarders-boards (focused on surfboards and riders) database with three main models: Boards, Riders, ...

The next.js Head component that is imported from next/head is not functioning correctly when used on share pages

I recently switched my website from create-react-app to create-next-app, but I'm having issues with the Head(app/head) component. Let's say I have a blog section with pages structured as follows: pages/blog/index.js and pages/blog/[slug].js. In ...

Encountering issues with accessing image files located in the public folder of my Next.js project - Receiving a 404 Error message

I am currently facing an issue with my Next.js project where I am unable to use image files from the public folder. Despite checking that the file paths, names, and extensions are correct, as well as ensuring my configurations are accurate, I keep encounte ...

Storing npm packages locally for faster build times on CircleCI

Currently, I am in the process of configuring CI for an existing Express server project located within the backend/core folder of my repository. Initially, I focused on setting up the basics such as installation and linting. While I have successfully enabl ...

What happens to the npm package if I transfer ownership of a github repository to a different user?

I was considering transferring a GitHub repository to another user or organization, but I have concerns about what will happen to older versions of the npm package associated with it. Let's say my Node.js package is named node-awesome-package. Versi ...

What is the best way to develop a widget that loads asynchronously by implementing AJAX, JavaScript, and PHP?

Currently, this widget is in need of items that are sourced from a php file. For instance, the javascript function should generate a table within this div element. <div id="widget"></> The aim is to dynamically update the content with the ht ...

The ajax form submit function does not have the capability to automatically post content

On this particular webpage, there is a visible form labeled form A which contains a submit button with a post action. <form name="payFormCcard" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> I am looking to cre ...

The functionality of the controls is not functioning properly when attempting to play a video after clicking on an image in HTML5

While working with two HTML5 videos, I encountered an issue with the play/pause functionality. Despite writing Javascript code to control this, clicking on one video's poster sometimes results in the other video playing instead. This inconsistency is ...

Incorporating and utilizing the HTML5-captured image as a point of reference

I understand that all I need to do to achieve this is insert <input type="file" id="photo" accept="image/*;capture=camera"> However, my lack of coding skills has caused issues with actually grabbing and using the image selected/taken by the user. ...

View Preview Image using the following image tag in JavaScript

I am trying to display an image preview using the img tag that is placed after my input field. Here is my HTML: <input name="image" type="file" id="uploadImage" onchange="PreviewImage(this);" /> ...

Exploring functional elements in Express and EJS

Within many MVC frameworks, there is often a feature that allows for actions to be invoked from the view. For ASP.NET MVC, this functionality is referred to as RenderAction, while other frameworks may call it SubActions, Viewlets, etc. In my EJS layout fi ...

How to retrieve the path, route, or namespace of the current or parent component/view in a Vue.js application

I have been working on enhancing a sub-menu system for vue.js that dynamically populates based on the children routes of the current route. I recently asked a question about this and received a helpful answer. Currently, I am trying to further improve the ...

Is there a way to initiate a jquery function upon loading the page, while ensuring its continued user interaction?

On my webpage, there is a JavaScript function using jQuery that I want to automatically start when the page loads. At the same time, I want to ensure that users can still interact with this function. This particular function involves selecting a link tha ...

Error in Angular form validation: Attempting to access property 'name' of an undefined value

Recently, I encountered an issue with my form while implementing Angular validation. The goal was to ensure that the input fields were not left blank by using an if statement. However, upon testing the form, I received the following error message: Cannot ...

Javascript handling scrolling and repositioning

When using the scrollBy() method in the window object of JavaScript, there are two arguments required. But what do these arguments actually represent? The resource I am currently studying from states that it is "the number of pixels to scroll by," but I am ...

What method would you recommend for monitoring a json file effectively?

Important Information: Currently, I am in the process of generating a json file via Matlab that constantly updates with the most recent coordinates. To accomplish this task, I have opted to utilize JsonLab for writing the file from Matlab to json. Dilemm ...

Upon submitting the form, the dynamic dependent drop-down list fails to offer any available options

Hey there, I've got a form with two drop-down lists: id="dd-1" & id="dd-2". The options in id="dd-2" are generated from the database based on what's selected in id="dd-1"; I'm using onChange=getChildOf(this.value) in id="dd-1" for this ...

Waiting for a Node.js/JavaScript module to finish running before proceeding

I've developed an express.js application that integrates with MongoDB using mongoose. Currently, I have the mongoose connection code stored in a separate file since it's used across multiple modules frequently. Below is the connector code: con ...