gpt4 book ai didi

javascript - 如何在 JavaScript 中延迟重试异步函数?

转载 作者:行者123 更新时间:2023-12-03 08:03:54 24 4
gpt4 key购买 nike

我正在尝试从数据库中获取记录。由于竞争条件,当我第一次尝试获取记录时,记录可能甚至可能不存在。我如何将其包装在重试逻辑中而不发疯?看来我太笨了

  const booking = await strapi.query("api::booking.booking").findOne({
where: {
id: id,
},
});

此代码应重试 n 次,延迟 t 毫秒。谢谢并充满爱意。

我尝试过的:

async function tryFetchBooking(
id,
max_retries = 3,
current_try = 0,
promise
) {
promise = promise || new Promise();

// try doing the important thing
const booking = await strapi.query("api::booking.booking").findOne({
where: {
id: id,
},
});

if (!booking) {
if (current_try < max_retries) {
console.log("No booking. Retrying");
setTimeout(function () {
tryFetchBooking(id, max_retries, current_try + 1, promise);
}, 500);
} else {
console.log("No booking. Giving up.");
promise.reject(new Error("no booking found in time"));
}
promise.catch(() => {
throw new Error(`Failed retrying 3 times`);
});
} else {
console.log("Found booking with retry");
promise.resolve(booking);
}
}

const booking = await tryFetchBooking(id);

抛出的错误:

This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason:
TypeError: Promise resolver undefined is not a function

最佳答案

那种promise.reject()/promise.resolve()方法是行不通的,你无法从外部解析一个promise。而且您不需要 - 只需从您的 async 函数中 return/ throw 即可!唯一需要构造新 Promise 的地方是在一个小辅助函数中

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

然后你可以以递归方式编写你的函数:

async function tryFetchBooking(
id,
max_retries = 3,
current_try = 0,
) {
let booking = await strapi.query("api::booking.booking").findOne({
where: {
id: id,
},
});

if (!booking) {
if (current_try < max_retries) {
console.log("No booking. Retrying");
await delay(500);
// ^^^^^^^^^^^^^^^^
booking = await tryFetchBooking(id, max_retries, current_try + 1);
// ^^^^^^^^^^^^^^^^^^^^^
console.log("Found booking with retry");
} else {
console.log("No booking. Giving up.");
throw new Error("no booking found in time");
// or if you prefer the other error message:
throw new Error(`Failed retrying 3 times`);
}
}
return booking;
}

或者甚至以迭代的方式:

async function tryFetchBooking(id, maxRetries = 3) {
let currentTry = 0;
while (true) {
const booking = await strapi.query("api::booking.booking").findOne({
where: {
id: id,
},
});

if (booking) {
return booking;
}
if (currentTry < maxRetries) {
await delay(500);
currentTry++;
} else {
console.log("No booking. Giving up.");
throw new Error("no booking found in time");
}
}
}

关于javascript - 如何在 JavaScript 中延迟重试异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73073043/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com