javascript - 使用 array.map、promises 和 setTimeout 更新数组

标签 javascript arrays node.js promise 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 - 使用 array.map、promises 和 setTimeout 更新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52030531/

相关文章:

javascript - javascript 中奇怪的关闭问题

通过取消引用其指针来计算数组的大小

c# - 如何与字符串数组和字符串进行比较

javascript - 如何将键值对象转换为对象数组

javascript - 为什么用 javascript 创建的文本框显示不同?

javascript - JavaScript 中 setInterval() 函数的用法

javascript - Canvas drawImage 不工作

javascript - 将 JavaScript 回调传递给在另一个线程中调用它的 FFI 函数是否安全?

node.js - 如何使用node.js中的事件流将可读流传输到child_process.exec命令?

javascript - 如何通过 CLI 自定义命令运行 Node 脚本?