我可以让 async.retry 方法即使在成功查询时重试但基于条件

can i make the async.retry method retry even on successfull queries but based on a condition

我正在研究 node.js 异步模块,我想知道是否有办法更改 async.retry 方法以重试,即使操作成功但会根据某些条件停止或响应假设它是一个 api 调用。

根据它的 docs ,该函数将继续尝试失败的任务,直到它 succeeds.if 它成功它只会 运行 只有那一次但是我怎样才能让它工作在成功的操作上也是如此,并使其在某些情况下停止?

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 untill the condition is met
        if (result.data.userId == 5) {
            // stop retring
        }
    });
};

retryPolicy(api);

我认为这是不可能的。 在 async.retry documentation 你可以找到这样的描述:

Attempts to get a successful response from task no more than times times before returning an error. If the task is successful, the callback will be passed the result of the successful task. If all attempts fail, the callback will be passed the error and result (if any) of the final attempt.

但是,使用给定的延迟函数 ,你可以用另一种方式做你想做的事:

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)
    }
   
    // do something
};

retryPolicy(api);

是的,如果不满足条件,您可以抛出自定义错误。会是这样的:

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);
        if(typeof result.data.userId != 'undefined' && result.data.userId == 5){ // change this condition to fit your needs
            return results.data;
        }else{
            throw {name : "BadDataError", message : "I don't like the data I got"}; 
        }
    } catch (error) {
        throw error;
    }
};