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

时间:2018-08-13 18:06:28

标签: javascript node.js api axios

我正在尝试使用从GET请求接收的数据填充数据库。每个请求返回500个项目,这又向数据库发出500个POST。共有686个GET请求。我遇到的问题是在第三个GET之后,我开始接收Error: connect EMFILE并最终在数据库中只有〜1700个项目。

我如何顺序/同步进行这些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);
}

1 个答案:

答案 0 :(得分:1)

这是对异步/等待的简单转换,我说过我会在评论中发布。

<div class="bg-white rounded scroll-screenshots mb-3">
      <div class="bg-white rounded js-screenshot-div screenshot-div d-flex pr-3 py-2">
        <div class="px-3 bg-white d-flex justify-content-center add-screenshot-button-div view-issue-screenshot-button">
          <button class="add-screenshot d-inline-block" id="add-screenshot-button">
            <div class="fa fa-camera" id="add-screenshot-icon"></div>
          </button>
        </div>
        <div class="js-screenshot-thumbnail-container issue-screenshots-flex d-flex">
            <a class="lightbox-image-link-small js-screenshot-lightbox rounded mr-2 border" href="http://localhost:5000/session_page/fa4a275bc2984895aaf0e60217b14ede/68/284/screenshot.png">
              <img src="http://localhost:5000/session_page/fa4a275bc2984895aaf0e60217b14ede/68/284/screenshot.png" alt="No Sample Box?" class="add-issue-screenshot rounded" id="screenshot-img">
            </a>
          </div>
      </div>
    </div>