javascript - 使用 array.map、promises 和 setTimeout 更新数组
问题描述
我希望遍历一组用户(仅设置 id 属性),每两秒使用每个 id 调用一个端点,并将响应中的关联用户名存储到更新的数组中。
例如更新 [{ id: 1 }]
到 [{ id: 1, name: "Leanne Graham" }]
这是我的代码:
const axios = require('axios');
const users = [{ id: 1 }, { id: 2 }, { id: 3 }];
function addNameToUser(user) {
return new Promise((resolve) => {
axios.get(`https://jsonplaceholder.typicode.com/users/${user.id}`)
.then(response => {
user.name = response.data.name
resolve(user);
});
})
}
const requests = users.map((user, index) => {
setTimeout(() => {
return addNameToUser(user);
}, index * 2000);
});
Promise.all(requests).then((updatedArr) => {
console.log(updatedArr);
});
没有 ,一切都很好setTimeout
,但重要的是我每两秒才发送一个请求。所以对于三个用户,我想Promise.all
在六秒左右后从我的日志中看到结果。
值得注意的是:这不是我正在处理的实际问题,而是我能想出的最简单的例子来帮助突出这个问题。
解决方案
据我了解,您问题的核心是如何将您的处理间隔 2 秒,对吗?
const users = [{ id: 1 }, { id: 2 }, { id: 3 }];
/* throttledProcess is a function that does your processing spaced by the given interval millisecond */
const throttledProcess = (items, interval) => {
if (items.length == 0) { // stop when there's no more items to process
console.log('ALL DONE')
return
}
console.log('PROCESSING', items[0], Date()) // this is where your http call/update/etc takes place
setTimeout(() => throttledProcess(items.slice(1), interval), // wrap in an arrow function to defer evaluation
interval)
}
throttledProcess(users, 2000) // run process. shows output every 2 seconds
运行此代码,每 2 秒,它将注销正在处理的用户。
希望这可以帮助。干杯,
推荐阅读
- javascript - 当 ng-model 设置为 false 时,仍然检查脏复选框
- html - 使文本倒置显示,CSS 和 HTML5
- sh - 将脚本作为服务运行的 Systemd 配置
- postgresql - 外键检查是在语句之后还是在每次修改之后运行?
- in-app-purchase - 来自 Google Play 的应用内购买
- css - 相同的样式表在浏览器和存储它的服务器上的显示方式不同
- solr - 匹配多值日期范围字段的单个值
- ruby-on-rails - 如何禁用 ActiveRecord::Migration 冗长?
- fluentd - Fluentd 不解析多行日志
- c++ - 在 gdb 中:在启动过程中程序以代码 1 退出。在 GDB 之外运行良好