This is more of a curiosity thing than a code not working thing.
It would seem that when using Async Functions in JS, mutating passed in variables works as one would expect, while reassigning them does not.
Here are two examples:
Arrays:
async function asyncResponse(x) {
return x
}
const anAsyncFunctionToUpdateArray = async(arrayToUpdate) => {
const res = await asyncResponse(3)
arrayToUpdate = arrayToUpdate.concat(res)
}
const anAsyncFunctionToUpdateArray1 = async(arrayToUpdate) => {
const res = await asyncResponse(1)
arrayToUpdate.push(res)
}
(async() => {
let anArrayToUpdate = []
anArrayToUpdate.push(2)
await anAsyncFunctionToUpdateArray(anArrayToUpdate)
await anAsyncFunctionToUpdateArray1(anArrayToUpdate)
console.log(anArrayToUpdate)
//expecting [2,3,1]
//but get [2, 1]
})()
Objects:
async function asyncResponse(x) {
return x
}
const anAsyncFunctionToUpdateObj = async(ObjToUpdate) => {
const res = await asyncResponse(3)
ObjToUpdate = {
...ObjToUpdate,
'baz': res
}
}
const anAsyncFunctionToUpdateObj1 = async(ObjToUpdate) => {
const res = await asyncResponse(1)
ObjToUpdate.fun = res
}
(async() => {
let anObjToUpdate = {}
anObjToUpdate.foo = 'bar'
await anAsyncFunctionToUpdateObj(anObjToUpdate)
await anAsyncFunctionToUpdateObj1(anObjToUpdate)
console.log(anObjToUpdate)
//expecting { foo: 'bar', baz: 3, fun: 1}
//but get { foo: 'bar', fun: 1}
})()
I tried googling for it, but I couldn't find anything quite explaining why reassignments don't work, but mutations do.
If anyone has an idea, or even a "duplicate: here's an old post about it" response, I'd love to hear from you.
Thanks!