Shopify API-获取所有产品(6万种产品),请求超时或套接字挂起

时间:2018-10-13 04:35:45

标签: node.js mongodb api promise shopify

我正在尝试获取所有产品,但在尝试为库存管理应用获取6万种产品时,请求超时。

我正在使用nodejs循环进入200页,每页限制为250个产品。我每10秒限制2个请求(5秒/ 1个请求)

有时我在某些页面上收到这些错误。有时不是

  • 读取ECONNRESET

  • 请求超时

  • 套接字挂起

请问我有什么问题吗?感谢您的帮助。

for (var i = 1; i<= totalPage;i++)

{

  var promise = shopify.product.list({limit:limit,page:i,fields:fields})

  .then(products =>{

  // do some thing here when got products list
    // loop through each product then save to DB
    // ShopifyModel.updateOne(.....)

  }).catch(error=>{

  // some time it fired error here 

  })

}
我还尝试重写一个函数以获取1页的产品:

const request = require('request-promise');

var getProductOnePage = function (Url_Page,headers,cb){
    request.get(productUrl, { headers: headers,gzip:true })
    .then((ListProducts) => {
        console.log(" Got products list of one page");
        cb(ListProducts);
    })
    .catch(err=>{
        // Got All Error Here when try to put into for loop or map or forEach with promise.all
        console.log("Error Cant get product of 1 page: ",err.message);
    });
}

编辑: 我在这里发现了一些与我的情况类似的问题: https://github.com/request/request/issues/2047 https://github.com/twilio/twilio-node/issues/312

2 个答案:

答案 0 :(得分:0)

您必须了解速率限制的概念。使用Shopify之类的任何公共API,您只能进行如此多的调用,然后才能将其搁置。因此,当您从Shopify返回响应时,可以检查标题中可以发出多少个请求。如果为零,则尝试请求将返回429。

因此,当您获得0的信用额度或429的返还额度时,您可以为自己设置一些超时时间,然后等待下一个通话。

如果另一方面,正如您所说,您每10秒仅进行2次呼叫(从代码中根本不清楚这样做的方式以及原因?),并且您超时了,那么您的Internet与Shopify的连接可能是问题所在。

答案 1 :(得分:0)

  • ECONNRESETRequest timed out错误主要是由于网络问题引起的。检查您的互联网连接是否稳定。

  • 如果您使用的是shopify api节点包,请使用autoLimit属性。它将解决速率限制问题。

例如:

const shopify = new Shopify({
    shopName: shopName,
    apiKey: api_key,
    password: password,
    autoLimit : { calls: 2, interval: 1000, bucketSize: 30 }
});

编辑:使用async等待,而不是先编写然后陷入for循环。因为天气您是否实现请求和等待方法,所以for循环将发送所有请求。但是,如果使用await,它将一次处理一个请求。

let getProducts = async () => {
    for (var i = 1; i<= totalPage;i++)
    {
        try {
            let products = await shopify.product.list({limit:limit,page:i,fields:fields});
            if(!products.length) {
                // all products have been fetched
                break;
            }
            // do you stuffs here
        } catch (error) {
            console.log(error);
        }
    }
}