我有一個包含很多專案的資料庫,我需要對這些專案中的每一個執行一個操作。不幸的是,我必須按順序運行這些操作,并且還要延遲每個操作以避免速率限制。
我的方法不會等待之前的操作完成,我最終會受到速率限制。為了使其按順序運行,我必須進行哪些更改?
setInterval(async () => {
await this.processQueue();
}, 1500)
private async processQueue() {
try {
//Only 3 requests per second allowed by the API so I only take 3 items from the database on every call
const bids = await getRepository(Bid).find({ order: { created_at: "ASC" }, take: 3, skip: 0 })
if (bids) {
for (const bid of bids) {
//check if active order exists
const activeOrder = await this.accountService.hasActiveOrder(bid.tokenId, bid.tokenAddress, 0);
if (!activeOrder) {
//perform async functions with that db item
const startTime = Date.now();
await this.placeBid(bid);
//delete from database so the next call to processQueue does not return the same itemsagain
await getRepository(Bid).delete({ id: bid.id })
const endTime = Date.now() - startTime;
}
}
}
} catch (error) {
console.error("TradingService processQeueu", error.message);
}
}
uj5u.com熱心網友回復:
您的間隔計時器與該processQueue功能正在完成的作業之間沒有協調。async將函式作為回呼傳遞給setInterval它是誤導性的并且沒有用處;setInterval不使用回呼的回傳值,因此它回傳的承諾不用于任何事情。
相反,最小的變化是使用等待完成processQueue的東西,也許是一系列鏈接的setTimeout回呼:
function processAndWait() {
processQueue().then(() => setTimeout(processAndWait, 1500));
// (Normally I'd have a `catch` call as well, but `processQueue`
// ensures it never rejects its promise)
}
請注意,在處理完佇列后等待 1500 毫秒。如果 API 允許每秒最多三個呼叫,這可能是矯枉過正。您可能可以將其修剪為 1000 毫秒。
或者,如果這是一個類中的方法(公共或私有):
processAndWait() {
processQueue().then(() => {
this.queueTimer = setTimeout(() => this.processAndWait(), 1500);
});
// (Normally I'd have a `catch` call as well, but `processQueue`
// ensures it never rejects its promise)
}
請注意,我添加了一些將計時器句柄保存到屬性的內容,因此您可以使用它clearTimeout(this.queueTimer)來停止行程。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/415435.html
標籤:
