javascript - 每 5 秒对特定数字重复一次操作,并且必须检查整个数组
问题描述
我必须检查这种安排中的所有值。整个数据分布变量称为“订阅用户”,我想知道当您尝试每 5 秒执行 10 次操作时是否有问题或更好的方法来创建以下逻辑。
let loopCount = 10;
let NumberOfBundle = Math.ceil(subscribingUser.length / loopCount); // 176
let restOfBundle = subscribingUser.length % loopCount; // 8
let bundleCount = 1;
let start = 0;
let bundleInterval = setInterval(async() => {
for(let i = start; i < loopCount; i++) {
//Perform 10 specific actions ...
await subscribingUser[i] ~
};
//Send all 10 and raise the BundleCount
bundleCount += 1;
start = loopCount;
if (bundleCount == NumberOfBundle && restOfBundle != 0) {
loopCount = restOfBundle - 1;
} else {
loopCount = loopCount * bundleCount;
}
if(bundleCount == NumberOfBundle + 1) {
clearInterval(bundleInterval);
}
}, 5000);
解决方案
- 首先,考虑避免
for(...){
await ...
}
因为您将按顺序执行您的工作,这否定了使用捆绑包的兴趣(并行处理捆绑包中的每个用户)
而是针对
await Promise.all(users.map(u => doSomethingWithUser(u)))
- 关于逻辑
您可以考虑将膨胀的东西从您的“客户”代码中分离出来
function bulker(arr, n) {
return {
async forEach (fn, binding) {
for(let i = 0; i < arr.length; i += n) {
await fn.call(binding, arr.slice(i, i + n), i, i +n >= arr.length)
}
}
}
}
const doSomethingWithUser = u => {
console.log('go', u);
return Promise.resolve(u)
}
;(async _=> {
//choose whenever you want to wait or not
//bulker just gives you the next slice once you "resolve"
await bulker([0, 1, 2, 3, 4], 2).forEach(async (users, i, done) => {
await Promise.all(users.map(doSomethingWithUser))
if (done) return
return new Promise((ok, ko) => setTimeout(ok, 1000))
})
console.log('done!')
})()
推荐阅读
- node.js - 将远程文件传递到 Node.js 应用程序中的 libreoffice-convert 库时收到“错误:没有这样的文件或目录,打开”
- autodesk-forge - 无法获取 /api/forge/oauth/callback
- python - 使用 pd.read_html 复制表
- python - POST 方法不适用于 Flask 应用程序 - 错误 404
- javascript - 无法对减速器中未安装的组件执行 React 状态更新
- python - 所以我正在处理一个 .csv 文件,发现在给定的数据中,事情的格式并不像他们应该的那样
- java - 用动画动态改变视图的宽度
- python-3.x - 如何在scrapy爬虫中使用代理?
- javascript - google sheet api javascript 使用超过 1 列对表格进行排序
- c++ - 如何在 Ruby 系统中运行 ARM 多线程程序