Utilizing Async/Await with an Unassigned Object

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.

Answer №1

After conducting a small test, it appears that in order to view the output, you should attempt fetching the 'data' property for printing in your specific case:

console.log('after assignment and value of tempPost in asyncForEach: ',tempPosts[tempPosts.indexOf(tempPost)]['data'])

However, when attempting to console.log(tempPost), the display of data will not occur unless the key has been defined in the TempPost's mongoose Schema.

If you wish to manipulate tempPost as a plain JavaScript object, you must convert the tempPost model document into a plain JavaScript object by utilizing toObject, such as tempPost = tempPost.toObject();. Following this action, your

console.log('after assignment and value of tempPosts in asyncForEach: ', tempPosts)
will yield the expected outcome.

Therefore, in my opinion, this issue is not necessarily related to async/await and assignment.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display dynamic content in a div using ajax and add animation effects, along with a "back" button functionality

I am in the process of creating a fantasy NFL web app using bootstrap and jQuery. Initially, I opted for Framework7 due to its user-friendly native app interface but decided to shift towards building a fully responsive page instead. Within my project, the ...

Avoiding future clicks with a delay in VUE: A guide

Is there a way to prevent the next click for 600ms after an initial click? I want to temporarily "disable" all a tags for 600ms after one is clicked. Any help would be appreciated. VUE <ul> <li v-for="item in navigation" :key=& ...

Issue with Moment.js amDateFormat consistently displaying date as 1970

Check out this link for more information I've integrated Moment.js and Angular-moment into my application. Oddly enough, all my epoch timestamps are being converted to the same date in 1970. <td class="timespan">{{tag.added_epoch | amDateForm ...

When an array is prototyped as a member of a JavaScript object, it becomes a shared property among all instances

Is anyone else surprised by this behavior? It really caught me off guard... I was expecting prototyped arrays to be private to each instance of a class rather than shared across all instances. Can someone confirm if this is the intended behavior and provi ...

What is the best way to save data from an ng-repeat array in MEANJS?

I've been exploring MEANJS at meanjs.org and I'm having trouble storing array data for ng-repeat in the deal object, which includes dealtype and dealprice. Despite setting up addFields for the ng-repeat input tag in the create form, the data isn& ...

What is the best way to split two sets of radio buttons with the same name into distinct blocks in an HTML form?

For my project, I am working with two sets of radio buttons where the values are stored in a Database. Depending on another result in the HTML form, I need to display one set of radio buttons or the other. The issue arises when using the same name for all ...

Send data to Jade template using variables

I've encountered an issue while attempting to send variables from page.js to page.jade, but unfortunately it is not working as expected. Here is the code snippet: page.js res.render('page', {param1: 'xxx', param2: 'yyy&apos ...

Some models showcase crisp textures with Thee.js, while others appear hazy (especially custom designs)

As a beginner in the realm of Three.js, I have been following a tutorial on texturing custom geometric shapes. The tutorial used a classic head OBJ file as a test case, which worked perfectly fine. However, when I tried to tweak the script to render my own ...

The app crashed unexpectedly with an error code of MODULE_NOT_FOUND and no requirestack

While attempting to run nodemon with the command "run start" on macOS, I encountered the following error message. Unsure if the operating system is a factor. ERROR node:internal/modules/cjs/loader:926 throw err; ^ Error: Cannot find module '/User ...

Is it feasible to utilize math.max with an array of objects?

When it comes to finding the largest number in an array, solutions like this are commonly used: var arr = [1, 2, 3]; var max = Math.max(...arr); But how can we achieve a similar result for an array of objects, each containing a 'number' field? ...

Utilize Ajax to transfer an image from an input form to a PHP script

I am currently working on a basic HTML page that includes an image upload form. Here is the code for the form: <input type='file' id='image_uploaded' accept='image'/> <input type='submit' id="upload_image"/ ...

When attempting to start the '.react-scripts' program, an error occurred stating that 'react-scripts' is not a recognized command, either internally or externally, and is not an

Currently, I am collaborating on an object detection model and have integrated it with a react frontend that I developed. Upon running the command 'npm start', I encountered an error message. You can view the specific error in the image I shared ...

The loading cursor in IE7 flickers incessantly, causing the webpage to lag and become un

When I move my cursor and click in text fields, the page becomes unresponsive and shows a wait cursor. If you're curious to see this issue in action, check out this video. This problem is specific to IE7. I've attempted to identify any ajax re ...

Using Ajax and jQuery to Retrieve the Value of a Single Tag Instead of an Entire Page

Let's say I have a webpage named page.html: <!doctype html> <html> <head> <meta charset="utf-8"> <title>Page</title> </head> <body> <h1>Hello World!!</h1> </body> </html> Now ...

The best approach to incorporating interactive animation in next.js

My vision is to develop a character creation application using next js. The app should empower users to customize the character using sliders and gender selection buttons. The ultimate goal is to have a 2D animated version of the character that dynamicall ...

Unable to understand the reason behind why the button is not being displayed

I'm having trouble with my quiz app. I have a button to submit answers and move on to the next question, but whenever I try to place it within the div that contains the quiz, the button disappears. Can someone please help me figure out what's wro ...

Fetching a Django view using an AJAX call and extracting the task_id from a Celery task

I have been facing a challenge trying to display data from a celery task in a separate window. My expertise in JavaScript and AJAX is limited, which is where I am encountering issues. Once a view is executed, the celery task commences and the subsequent HT ...

What could be causing the CSS to not display properly on specific routes?

I'm facing an issue where CSS seems to be working fine for certain routes with node.js & express, but not for others. It's puzzling because the HTML file links to the same CSS file in both cases. For instance, CSS works perfectly for the route " ...

a single function spread across two controllers[JavaScript]

My query pertains to a JavaScript program with 2 controllers. The issue I am facing is the need for one function in both controllers (data.duration). This function serves two purposes, once for features themselves and once for the summary. Currently, this ...

Changing Underscores in ES6 Techniques

My current project is built using AngularJS, Redux, and Underscore. Within this project, I have the following code snippet: const selectedBroker = _.findWhere(state.brokers, { brokerId: action.payload }); return state.merge({ selectedBroker, sel ...