【发布时间】:2021-08-24 13:39:47
【问题描述】:
概述
我在 AWS lambda 上使用 NodeJs 中的异步映射函数时遇到了一些奇怪的行为,我很想知道为什么会发生这种情况。
我在下面的代码块中重新创建了一个玩具示例,其中给出了错误的代码。
topLevel() 函数有一个对象数组。该函数在数组上调用 Array.map(),并将异步辅助函数传递给 map 函数。辅助函数对对象执行一些转换,其中一种转换是加密银行帐户嵌套对象。这是通过另一个异步辅助函数 (encryptBank) 完成的。
虫子
在topLevel函数的返回值中,id="abc"用户的银行账户有来自id="def"用户的加密银行账户对象。 id="def" 的用户拥有正确的加密银行账户对象。
什么可能导致这种情况发生?从异步映射函数调用异步函数有问题吗?在 Array.map() 中使用异步函数是个坏主意吗?任何提示都将不胜感激,因为这个错误一直让我发疯。
环境信息
使用 NodeJS(版本 12)运行时在 AWS Lambda 上运行。
代码
// This is the lambda handler
module.exports.topLevel = async () {
const users = [
{
id: 'abc',
name: 'George P. Burdell',
job: 'Jack of all trades',
married: true,
bankInformation: {
institution: 'Bank of America',
routingNumber: 987654321,
accountNumber: 665471235774
}
},
{
id: 'def',
name: 'Jay-Z',
job: 'Artist',
married: true,
bankInformation: {
institution: 'Chase',
routingNumber: 123456789,
accountNumber: 97822651348
}
}
]
const transformedUsers = await Promise.all(users.map(helper))
return transformedUsers
}
async function helper(o) {
Object.Keys(o).forEach((k) => {
if (k === 'bankInformation') {
o[k] = await encryptBank(o[k])
await s3.putObject({Body: JSON.stringify(o[k]),Bucket: bankBucketName, Key: `${o.id.toLowerCase()}.json`}).promise()
} else if (k === 'married') {
o[k] = !o[k]
}
else {
o[k] = k.toUpperCase()
}
})
return o
}
async function encryptBank(o) {
Object.Keys(o).forEach((k) => {
o[k] = await encrypt(o[k])
})
return o
}
【问题讨论】:
标签: node.js asynchronous memory