[英]How to add delay inside async forEach loop
I have a trading script that gets values from "coin" object, which is filled by an API call, then iterates inside async forEach
loop, then sends trade orders to the server.我有一个从“coin”对象获取值的交易脚本,该对象由 API 调用填充,然后在async forEach
循环中迭代,然后将交易订单发送到服务器。
The server requires at least 100 ms between each request.服务器在每个请求之间至少需要 100 毫秒。 I used setTimeout
with promise, but I can see results coming to console all at once so server bans after a while.我将setTimeout
与 promise 一起使用,但我可以看到结果同时进入控制台,因此服务器在一段时间后被禁止。
How should I design delaying?我应该如何设计延迟?
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));
});
Use for
loop instead of forEach
and wrap the whole stuff into an async function:使用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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.