【发布时间】:2021-03-19 14:57:35
【问题描述】:
我有一组用户。我需要在每个user.id 上调用“costlyEncryptionFunction”,但我不想在同一个user.id 上多次调用“costlyEncryptionFunction”。
这是一个工作示例:
const costlyEncryptionFunction = async (id) => {
return new Promise((res) => {
setTimeout(() => {
res(id + 1000)
}, 1000)
})
}
let users = [
{id: 1, item: 1},
{id: 1, item: 2},
{id: 2, item: 5},
{id: 2, item: 6}
]
let currentUserId
users.map(async (user) => {
let encryptedUserId
if(!currentUserId || currentUserId != user.id){
currentUserId = user.id
encryptedUserId = await costlyEncryptionFunction(currentUserId)
}
if(encryptedUserId){
console.log(`inside: ${encryptedUserId} ${user.item} ... do more stuff` )
}
})
输出读取
inside: 1001 1 ... do more stuff
inside: 1002 5 ... do more stuff
我正在尝试读取我的输出:
inside: 1001 1 ... do more stuff
inside: 1001 2 ... do more stuff
inside: 1002 5 ... do more stuff
inside: 1002 6 ... do more stuff
除了调用“costlyEncryptionFunction”并多次重复相同的userId 之外,有没有人对此有解决方案?
【问题讨论】:
-
记忆函数?
标签: javascript arrays async-await