I was trying out some things with async/await and for some reason my function runs before my await is finished, can someone tell me why?
(function() {
var posts = [{
title: "Post 1",
body: "This is post 1"
},
{
title: "Post 2",
body: "This is post 2"
},
{
title: "Post 3",
body: "This is post 3"
}
];
function GetPosts() {
setTimeout(() => {
let output = '';
posts.forEach((post, index) => {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
}, 1000);
}
function CreatePost(post) {
setTimeout(() => {
posts.push(post);
}, 4000);
}
async function init() {
await CreatePost({
title: "Post 4",
body: "This is post 4"
});
GetPosts();
}
init();
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>