重试请求,直到结果返回值

时间:2019-01-28 15:30:03

标签: javascript node.js

我有一个API从后端服务请求一些数据。

第一次请求时数据可能不是它们的。因此,我想重试5次,直到出现数据为止。

我知道返回给我的数组不为空时数据存在

获取分类结果

 public async processClassification(instanceId: any, requestId: any): Promise<any> {

        const url = this.config.backendUrl + "/check/classification";

        const options = {
            uri: url,
            headers: {
                "X-IDCHECK-SESSION_ID": instanceId,
            },
            body: {},
            json: true,
            resolveWithFullResponse: true,
        };

        let classification;

        try {

            classification = await request.get(options);

            if (classification.statusCode !== 200) {
                return {
                    success: false,
                    error: classification,
                    message: "Failed to process classification",
                };
            }

            return {
                success: true,
                data: classification,
                message: "Successfully processed classification",
            };

        } catch (err) {

            return {
                success: false,
                error: err.stack,
                message: "Server threw an unexpected error during processClassification",
            };

        }

    }

上面是一个简单的函数,它一次查询后端http以获得分类结果。如果没有结果,则数组result.body.data.classification将为空。

如何修改此代码以最多重试5次。

请不要被打字稿推迟,我会接受js答案。

2 个答案:

答案 0 :(得分:0)

如果请求未返回任何数据并传递尝试次数,则使用递归再次调用该函数。

如果尝试次数超过最大次数,则最终throw出错。

// Mock request, resolves filled array if value is 5, 
// resolves empty array otherwise.
const request = value => {
  return new Promise(resolve => {
    setTimeout(() => {
      value === 5 ? resolve(['foo', 'bar']) : resolve([])
    }, 500)
  })
}

const retry = async (times, attempts = 0) => {
  attempts++
 
  console.log('Attempt', attempts)
 
  const result = await request(attempts)
  
  if (result.length) {
    return result
  } else {
    if (attempts >= times)
      throw new Error('Max attempts exceeded')

    return retry(times, attempts)
  }
}

retry(5)
  .then(console.log)
  .catch(console.error)

答案 1 :(得分:-1)

您可以尝试使用此软件包https://github.com/IndigoUnited/node-promise-retry