我正在尝试从数据库中获取一条记录。由于争用条件,当我第一次尝试获取记录时,记录可能甚至很可能不存在。我如何将其 Package 在重试逻辑中而不出错?我似乎太笨了,做不到这一点
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
3条答案
按热度按时间fslejnso1#
这种
promise.reject()
/promise.resolve()
的方法是行不通的,你不能从外部解决一个承诺。你不应该需要--只需要从你的async
函数中构造return
/throw
!你唯一需要构造new Promise
的地方是在一个小的helper函数中然后你可以用递归的方式来写你的函数:
或者甚至以迭代的方式:
nhn9ugyo2#
使用的模拟:
4nkexdtk3#
为了避免在循环中使用
await
,可以使用递归函数调用tryFetchBooking