【问题标题】:How to retry API once a specific field of response is ready?一旦特定的响应字段准备好,如何重试 API?
【发布时间】:2022-02-14 22:00:46
【问题描述】:

我尝试调用的 API 的响应字段之一只有在一段时间后才准备就绪。

一旦准备好获取该字段,我如何获取它?

const apiState = Date.now();
const callApi = () => Promise.resolve({
  field: "xxx",
  asyncField: Date.now() - apiState > 10000 ? "aaa" : undefined
});

async function waitForApiReady() {
  const response = await callApi();
  console.log({ response });
  //response.asyncField is undefined at this moment, but it will ready after 10secs or later.
  return response.asyncField;
}

waitForApiReady().then(console.log).catch(console.log);

【问题讨论】:

  • callApi 是对发出 http 请求的真实函数的模拟,还是您的实际代码?
  • @Bergi,它只是一个模拟。
  • 这个setTimeout呢?在你的真实代码中设置asyncField的过程是什么?
  • @Bergi,对不起,没有冒犯,你能再读一遍这个问题吗?我一开始调用它时有 api,它没有 asyncField,因为数据正在准备那一刻。 10 秒后,数据准备好了,当我再次调用它时,它将包含 asyncField 中的数据。问题是准备时间可能不同,可能是 10 秒或 20 秒。
  • 所以API每次都返回一个新的对象,在一段时间后调用API时,它会返回一个带有字段的对象吗?它不会修改先前返回的对象吗? “一旦准备好获取该字段,我如何才能获取它?”听起来您会知道该字段何时准备好获取。

标签: javascript promise


【解决方案1】:

您可以设置一个 while 循环来继续调用 API,并且仅在收到响应时返回。

另外,wait 功能是延迟每次调用以不使用您的程序。

const apiState = Date.now();
const callApi = () => Promise.resolve({
  field: "xxx",
  asyncField: Date.now() - apiState > 10000 ? "aaa" : undefined
});

const wait = ms => new Promise((resolve) => setTimeout(resolve, ms));

async function waitForApiReady() {
  let output;
  while (true) {
    const response = await callApi();
    console.log(response);
    if (response.asyncField) {
      output = response.asyncField;
      break;
    }

    await wait(5000);
  }

  return output;
}

waitForApiReady().then(console.log).catch(console.log);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-04
    • 2020-05-05
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多