I am trying to learn the concepts of async/await in javascript. I tried a simple code, to wait for a create post function to finish before calling the getPosts function, but the newly created post is not showing up. This is what I have tried out.
const posts = [{
title: "Post One",
body: "This is post one"
},
{
title: "Post Two",
body: "This is post two"
}
]
const newpost = {
title: "Post Three",
body: "This is post three"
}
function getPosts() {
setTimeout(() => {
let output = '';
posts.forEach((post, index) => {
output += `<li>${post.title} : ${post.body}</li>`;
});
document.body.innerHTML = output;
}, 1000);
}
function createPost(post) {
setTimeout(() => {
posts.push(post);
}, 2000);
}
async function init() {
await createPost(newpost);
getPosts();
}
init();
Can anyone point out what I am doing wrong?