我正试图开发一个电子商务网站的后端使用Stripe和NodeJS (准确地说)。
当服务器启动时,我试图从Stripe中获取我的产品。但是,在第一个stripe.products.list
调用之后,我得到一个错误,它说我超过了api的速率限制。这不是真的,因为正如它在条纹医生中所说,在测试模式下,速率限制在25/秒,而我在进行第二次调用之前等待10秒。
请在下面找到我打电话的功能。我只是在循环中使用它,在每次调用之前都有一个loop ()函数。
async function fetchFromLastObj(last_obj){
const data = stripe.products.list({
active: true,
limit: maxRetrieve,
starting_after: last_obj,
})
.then((resp) => {
console.log(`Retrieved ${resp.data.length} products.`);
return resp.data;
})
.catch((e) => { });
return data;
}
睡眠功能:
const { promisify } = require('util')
const sleep = promisify(setTimeout)
所讨论的循环:
var last_obj_seen = null;
var nb_iters = 0;
// fetching all products from stripe
while (true) {
console.log(`Iteration ${nb_iters+1}...`)
let fetchedList = [];
if (last_obj_seen == null) {
fetchedList = await fetchFirstBatch();
} else {
fetchedList = await fetchFromLastObj(last_obj_seen);
}
fetchedList = Array.from(fetchedList);
if (fetchedList.length == 0) { break; };
last_obj_seen = fetchedList.slice(-1)[0];
await sleep(10000);
fetchPrices((fetchedList))
.then((fetchedListWithPrices)=>{
saveList(fetchedListWithPrices);//not asynchronous
})
.catch((err) => { console.error("While fetching products from Stripe..."); console.error(err); });
nb_iters += 1;
if(nb_iters > 100){ throw Error("Infinite loop error"); }
if (nb_iters !== 0){
console.log("Waiting before request...");
await sleep(10000);
}
}
console.log("Done.");
发布于 2021-08-26 11:35:57
您可以使用官方条形库的自动分页功能,而不是自己处理分页逻辑。
我们的图书馆支持自动分页。这个特性可以轻松地处理获取大量资源列表,而无需手动分页结果和执行后续请求。
在Node 10+中,您可以这样做,例如:
for await (const product of stripe.products.list()) {
// Do something with product
}
条形节点库将为您处理引擎盖下的分页操作。
https://stackoverflow.com/questions/68943305
复制相似问题