What could be the reason for the failure of the async await implementation in this particular code sample?

While attempting to follow a tutorial on YouTube, I encountered an issue where the code didn't work as expected. Can anyone lend a hand in helping me figure out what might be going wrong?

let posts = [
  {name: '1', data: 'Hi1'},
  {name: '2', data: 'Hi2'},
]

function getPosts() {
  setTimeout(()=> {
    posts.forEach((post) => {
      console.log(post.name)

    })
  }, 1000)
}

function createPost(post) {
  setTimeout(()=> {
    posts.push(post)
  }, 2000)
  
} 



async function init() {
  await createPost({name: '3', data: 'hey'})
  getPosts()
}

init();

Answer №1

The asynchronous nature of createPost is causing getPost() to execute before createPost has completed, resulting in the posts variable not having the 3rd item at that time.

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

Having trouble changing the Font Awesome icon on click?

I'm struggling to figure out why I can't change a font awesome icon using a toggle. I've tried various solutions but nothing seems to be working. Any insights on what might be causing this issue? (HTML) <span class="toggle-icon" ...

Tips for implementing X-XSS-Protection: 1; mode=block in HTML

I'm struggling with where to place this piece of code in my existing code. Should it be added to the header section? <head> <meta content="text/html; charset=UTF-8; X-Content-Type-Options=nosniff" http-equiv="Content-Type" /> <title> ...

What is the best way to showcase the content from multiple uploaded files?

Below is an example demonstrating how to display the contents of a single uploaded file. .js $scope.uploadFilename = function (files) { if (!files[0]) { return; } var reader = new FileReader(); reader ...

Encountering Babel issues while incorporating npm package into React Native project

Currently, I am developing a React Native application. In an attempt to enhance my application, I decided to incorporate the npm package available at this link: https://github.com/MagicTheGathering/mtg-sdk-javascript/ Despite trying various import statem ...

Parsing error: Unforeseen token encountered. Consider adding a supplementary loader to manage the output of these loaders

Could someone please break down this syntax message?.length === 1 and show me how to convert it into standard JavaScript? https://i.stack.imgur.com/20Ui6.png I am encountering an error when trying to use a Vue.js component that I downloaded from another ...

Using jQuery to reset the position of animated divs

I am currently working on a code that expands and centers a div when hovered upon using the following script: $(document).ready(function(){ //animation on hover $('#sliding_grid li').hover(function() { ...

What is the best way to invoke a Rest API within a Vue component?

As a newcomer to VueJS, my goal is to create a basic page featuring a pie chart displaying some data. Currently, I have successfully displayed the chart using example data. However, I now wish to populate the chart with data fetched from an API call on my ...

Transferring information from offspring to parent

Greetings! I'm currently getting my feet wet with React and finding myself stuck on an issue regarding passing states. Is it possible for me to pass a child state to a parent component in order to selectively render other child components? ...

Adding a prefix to all specified routes in Express.js

Imagine having an Express app defined in a file called server.js as follows: const app = express(); app.use('/foo', foo); app.use('/bar', bar); module.exports = app; You then import this Express app into another file named index.js: ...

What is the best way to retrieve the chosen option when clicking or changing using jQuery?

CSS <form name='category_filter' action='/jobseek/search_jobs/' method='get'> <select id="id_category" class="" name="category"> <option value="" selected="selected">All</option> <option v ...

Optimal techniques for leveraging CSS within Mui and Reactjs

Just starting out with mui, I'm currently working on styling CSS for mui components like so <Typography variant="h5" sx={{ fontWeight: "bold", color: "#1a759f", display: "flex", ...

The watermark feature in HTML may not appear when printed on every page

I'm facing an issue with adding a watermark style. The watermark displays only on the first page when attempting to print in Chrome. It works perfectly in Firefox and IE. <style type="text/css"> #watermark { color: #d0d0d0; font-size: 90pt; ...

Utilizing the Django object array in AngularJS – a comprehensive guide

I have a Django variable structured like this: [<Topic object>, <Topic object>] When passing it to Angular using ng-init, I wrote the following: <div class="profile-navigation" ng-init="ProfileTopics={{ProfileTopics|safe}} "> However, ...

What is the best way to style HTML content with MathJax following its retrieval with jQuery.load?

I recently encountered an issue while using jQuery.load to load a new page. The content on the original page is being treated strangely in some way. Specifically, I have code on the original page that formats LaTeX commands with MathJax: <script type=" ...

What was the reason for needing to employ `toObject()` in mongoose to determine if an object contains a certain property?

From what I understand, there is no .toObect() function in JavaScript, but it is used in mongoose to convert mongoose documents into objects so that JavaScript built-in functions can be used. I sometimes struggle with when to use it. There are instances w ...

What advantages does incorporating SSR with dynamic imports bring?

How does a dynamic imported component with ssr: true differ from a normal component import? const DynamicButton = dynamic(() => import('./Button').then((mod) => mod.Button), { ssr: true, }); What are the advantages of one method over the ...

Is it possible to capture and generate an AxiosPromise inside a function?

I am looking to make a change in a function that currently returns an AxiosPromise. Here is the existing code: example(){ return api.get(url); } The api.get call returns an object of type AxiosPromise<any>. I would like to modify this function so ...

"Can you share how to send an array of integers from a Jade URL to an Express.js route

I am currently working on creating an array of integers in JavaScript using the Jade template engine. My goal is to send this array to an Express.js route when a button is clicked. I have attempted the following code: Jade File: //Passing the ID to fu ...

What is the best way to display the data model in Angular as HTML?

I am facing an issue with my data-model where it needs to be converted or displayed as HTML, but currently it is only appearing as plain text. Here is the HTML code snippet: <div ng-repeat="item in ornamentFigures" class="ornament-item"> <la ...

What is the best way to showcase a PDF file on a webpage with multiple thumbnails using JavaScript or jQuery?

I recently undertook a project at work that involved displaying multiple PDF thumbnails/images on a webpage. These files were dynamically loaded from a directory on my system. Each thumbnail corresponded to a PDF file stored in a different directory. My g ...