【问题标题】:How to add delay inside async forEach loop如何在异步 forEach 循环中添加延迟
【发布时间】:2020-04-25 00:00:08
【问题描述】:

我有一个交易脚本,它从“coin”对象中获取值,该对象由 API 调用填充,然后在 async forEach 循环内进行迭代,然后将交易订单发送到服务器。

服务器要求每个请求之间至少有 100 毫秒。我承诺使用setTimeout,但我可以看到结果立即出现在控制台上,因此服务器会在一段时间后被禁止。

我应该如何设计延迟?
js

Object.keys(coin).forEach(async function(key) {
 const coinz = coin[key];
  let line1 = sellcoinCalc("sell", coinz.usdPair, coinz.usdOrder)
  let line2 = buycoinCalc("buy", coinz.usdtPair, line1)          
  let result = line2-line1
 if (result > 0){
  console.log(result)
  }
 if (result >= profit){
      await sellcoinTrade("sell", coinz.usdPair, coinz.usdOrder)
      await buycoinTrade("buy", coinz.usdtPair, line1)            
  }
      await new Promise(r => setTimeout(r, 200));
  });

【问题讨论】:

  • 这能回答你的问题吗? How do I add a delay in a JavaScript loop?
  • 你可以使用 setTimeout 函数
  • 另一种解决方案是使用 rxjs 库中的流。
  • 我需要异步函数中的解决方案
  • 为了使其工作,forEach 回调必须是 await 由 forEach 的内部工作原理。很确定不是这样的。您将不得不以其他方式添加等待部分。

标签: javascript loops foreach async-await settimeout


【解决方案1】:

使用 for 循环而不是 forEach 并将整个内容包装到异步函数中:

const sleep = ms => new Promise(r => setTimeout(r, ms))

const tradeFn = async () => {
  try {
    for (let i in coin) {
      await sleep(200);
      const coinz = coin[i];
      await sellcoinTrade(coinz /* etc */);
      // etc
    }
  } catch(e) {
    // handle rejections
  }
}

【讨论】:

  • 我必须使用 for 循环吗? , forEach 方法对于复杂的硬币对象更简单
  • 是的,但由于某种原因不能异步工作。这个基本的for 循环或for (let i in coin) 解决方案将起作用。
  • 您也可以使用 for...await 循环,但它需要自定义迭代器函数。
猜你喜欢
  • 2021-05-30
相关资源
最近更新 更多