API 调用之间的延迟 Node.js

问题描述 投票:0回答:0

我有一个 jquery $.each 循环将不同的变量提供给 POST API 调用。我试图将每个变量之间的 API 调用延迟 5 秒,但即使使用 setTimeout,它也会同时执行。

var skuList = require('../inputSKU.json');

const url = www.someurl.com

const query = `query example xyz`

//the problem below

$.each(skuList.list, function getData(i, e) {
  var variables = e;
  
  var body = JSON.stringify({
    query,
    variables
  })
  var resJSON = '';
  var a = '';

  setTimeout(async () => {
    var res = await fetch(url,
      {
        method: 'POST',
        body: body,
        headers: {
          'Content-Type': 'application/json',
          'Content-Length': body.length,
          "Accept": "application/json",
          'x-gql-access-token': '8635be91-b771-11ed-aa31-49d35f4239b3',
          'x-gql-country': 'US'
        }
      }
    )

    a = await res.json();

    resJSON = a.data;

    console.log(resJSON)

  }, 5000);

这将快速启动 console.log resJSON。有添加延迟的优雅解决方案吗?

如果我使用带索引的 for 循环,似乎有解决方案。

for(var i in list) { // list is an array, i is current index
  setTimeout(function() {
    apicall()
  }, 1500 * i) // With each iteration, the delay increases
}

对于 $.each 可能是这样的?

javascript jquery node.js api each
© www.soinside.com 2019 - 2024. All rights reserved.