【问题标题】:ECONNRESET and SOCKET HANG UP errors when trying to send Requests to Google API with node.js尝试使用 node.js 向 Google API 发送请求时出现 ECONNRESET 和 SOCKET HANG UP 错误
【发布时间】:2020-08-16 17:13:49
【问题描述】:
我正在使用 Google 的 node.js API 库将产品数据发送到 Google 商家中心。
在大约 30% 的请求中,我收到以下错误:
我认为原因可能是请求发送速度很快并且达到了 API 的配额限制。
我可以使用哪种方法来限制对 API 的请求数?我试过了
setTimeout(() => { null }, 3000);
每次在发送 API 请求之前,但看起来它并没有改变任何东西。
【问题讨论】:
标签:
node.js
google-api
google-api-nodejs-client
【解决方案1】:
这是该问题的解决方案。我添加了一个返回 Promise 的等待方法。
while((batchOffset + batchSize) <= products.length) {
const entries = [];
const productsBatch = products.slice(batchOffset, (batchOffset+batchSize));
// Wait between API calls to avoid hitting Google API quota limits
await this.wait(100);
// Send a batch of n products to Google content API
contentApi.products.custombatch(
{
requestBody: {
entries: entries,
},
},
(err, res) => {
// handle err and response
if (err !== null || res.status !== 200) {
this.logger.log(
'error',
'...'
);
} else {
this.logger.log(
'info',
'...',
);
}
},
);
batchOffset+=batchSize;
}
......
private wait(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms))
}