延迟脚本在等待获取时循环

时间:2015-12-12 14:39:02

标签: javascript fetch pipedrive-api

在下面的脚本中,我需要在每次提取运行时添加一个等待,如果我发送它们太快,pipedrive将无法正常更新。我尝试过setTimeout,但它没有用......有什么想法吗?

var response = [{
  id: 118,
  deal_id: 329,
  item_price: 53.37,
  quantity: 6
}, {
  id: 119,
  deal_id: 329,
  item_price: 69.07,
  quantity: 6
}];

var txtStr = '';
var myurl = '';
var mybody = '';

for (var i = 0; i < response.length; i++) {
  txtStr = txtStr + response[i].id;
  myurl = "https://api.pipedrive.com/v1/deals/" + response[i].deal_id + "/products/" + response[i].id + "?api_token=123456";
  mybody = JSON.stringify({
    'id': response[i].id,
    'deal_product_id': response[i].deal_id,
    'item_price': response[i].item_price,
    'quantity': response[i].quantity,
  })

  fetch(myurl, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: mybody
    })
    .then(function(response) {
      var produto_id = response.id;
      return response.text();
    }).then(function(body) {
      var output = {
        response: body
      };
      callback(null, {
        id: 123,
        rawHTML: body
      });
    }).catch(function(error) {
      callback(error);
    })
}

1 个答案:

答案 0 :(得分:0)

由于这是异步,将你的提取放入一个que,然后在你的回调上,检查数组以查看是否有另一个提取等待。