I'm facing a puzzling issue with an async/await function that refuses to assign to an object. Despite displaying the expected results in the console, when it comes to actually assigning to the object, it fails to do so. Let me elaborate below:
Here's the snippet of code in question:
This function serves as a helper for asyncForEach:
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
Then there's the following piece of code:
const asyncFunc = async () => {
await asyncForEach(tempPosts, async (tempPost) => {
if (tempPost.fileName!=''){
console.log('tempPosts[tempPosts.indexOf(tempPost)]: ',
tempPosts[tempPosts.indexOf(tempPost)])
console.log("await fsPromise.readFile(__dirname+'/../picFolder/sharp/'+tempPost.fileName)",
await fsPromise.readFile(__dirname+'/../picFolder/sharp
/'+tempPost.fileName))
tempPosts[tempPosts.indexOf(tempPost)]['data'] =
await fsPromise.readFile(__dirname+'/../picFolder/sharp/'+tempPost.fileName)
console.log('after assignment and value of tempPosts in asyncForEach: ', tempPosts)
}
})
}
Following are the outputs of the three javascript logs:
console.log('tempPosts[tempPosts.indexOf(tempPost)]: ',
tempPosts[tempPosts.indexOf(tempPost)])
Outputs
tempPosts[tempPosts.indexOf(tempPost)]: { flags: 0,
fileName: '1552601360288&&travelmodal.png',
comments: [],
_id: 5c8ad110ef45f6e51a323a18,
body: 'asdasdfasdf',
created: 2019-03-14T22:09:20.427Z,
__v: 0 }
Seemingly correct.
And
console.log("await fsPromise.readFile(__dirname+'/../picFolder/sharp/'+tempPost.fileName)",
await fsPromise.readFile(__dirname+'/../picFolder/sharp
/'+tempPost.fileName))
Yields...
await fsPromise.readFile(__dirname+'/../picFolder/sharp/'+tempPost.fileName)
<Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00
...
The desired long data buffer string is obtained. Excellent!
HOOTENANNY
after assignment and value of tempPosts in asyncForEach: [ { flags: 0,
fileName: '1552601360288&&travelmodal.png',
comments: [],
_id: 5c8ad110ef45f6e51a323a18,
body: 'asdasdfasdf',
created: 2019-03-14T22:09:20.427Z,
__v: 0 },
{ flags: 0,
fileName: '1552601320137&&Screen Shot 2019-03-09 at 10.03.09 AM.png',
comments: [],
_id: 5c8ad0e8ef45f6e51a323a17,
body: 'adf',
created: 2019-03-14T22:08:40.336Z,
__v: 0 } ]
Wait, what? I use
Object['newKey'] = await fsPromise.readFile(yadayada)
, where await fsPromise.readFile(yadayada)
works in a console log. Yet, this seems to be ineffective. This is mind-boggling.