0

Was following a tutorial on youtube but unfortunately didn't work. Any chance someone could tell me where I am 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();
snasri8
  • 11
  • 1
    1. neither `getPosts` nor `createPost` returns a promise, so `await` has (basically) no effect here. 2. `setTimeout` doesn't return a promise, either, you cannot `await` that even if you had returned its value. [Unless you convert it to a promise](https://stackoverflow.com/a/39914235/) – VLAZ Jan 26 '21 at 19:19

1 Answers1

0

Your createPost is not an async function so getPost() doesn't wait for createPost to be finished so it runs instantly. And by that time posts variable doesn't have the 3rd item.

Saad
  • 36
  • 5