A callback is simply a function that’s passed in as a parameter to another function and then it’s ran inside the function body. So whenever we did a foreach on an array when we do array for each and then we pass in function. That’s actually a callback.
const posts = [
{ title: 'Post One', body: 'This is post one' },
{ title: 'Post Two', body: 'This is post two' }
]
function createPost(post, callback){
setTimeout(function(){
posts.push(post);
callback();
}, 2000);
}
function getPost(){
setTimeout(function(){
let output = '';
posts.forEach(function(post){
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
}, 1000);
}
createPost({ title: 'Post Three', body: 'This is post Three'}, getPost);
getPost();
Leave a Reply