简体   繁体   English

如何顺序/同步进行API调用-EMFILE错误

[英]How to sequentially/synchronously make API calls - EMFILE error

I am trying to populate a database with data received from GET requests. 我正在尝试使用从GET请求接收的数据填充数据库。 Each request returns 500 items, which in turn makes 500 POSTs to the database. 每个请求返回500个项目,这又向数据库发出500个POST。 There are 686 GET requests to be made. 共有686个GET请求。 The problem I am having is after the third GET, I start receiving Error: connect EMFILE and ended up with only ~1700 items in the database. 我遇到的问题是在第三个GET之后,我开始收到Error: connect EMFILE并最终在数据库中只有〜1700个项目。

How would I make these API calls sequentially/synchronously to avoid this? 我如何顺序/同步进行这些API调用以避免这种情况?

 function getProducts(myUrl) { axios.get(myUrl, { httpsAgent: agent }) .then(res => { res.data.products.forEach(product => { var product = { 'values': { '2': product.name, '3': product.display_price, '4': product.slug } }; postProduct(product); }); }) .catch(err => { console.log(err); }); } function postProduct(product) { axios.post(huburl, product) .then(res => { console.log(res.data); }) .catch(err => { console.log(err) }); } for (let i = 1; i <= 686; i++) { var pagedUrl = url + '&page=' + i; console.log(pagedUrl); getProducts(pagedUrl); } 

Here is a simple conversion to async/await that I said I would post in the comments. 这是我说过要在评论中发布的对async / await的简单转换。

 async function getProducts(myUrl) { try { let res = await axios.get(myUrl, { httpsAgent: agent }); res.data.products.forEach(product => { var product = { 'values': { '2': product.name, '3': product.display_price, '4': product.slug } }; await postProduct(product); }); } catch (e) { console.log(e); } } async function postProduct(product) { try { let res = await axios.post(huburl, product); console.log(res.data); } catch (e) { console.log(e); } } for (let i = 1; i <= 686; i++) { var pagedUrl = url + '&page=' + i; console.log(pagedUrl); await getProducts(pagedUrl); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM