Synchronous operation
const posts = [
{title: "Post One", body: "This is post one"},
{title: "Post Two", body: "This is post two"}
];
function createPost(post) {
setTimeout(function () {
posts.push(post);
}, 2000);
}
function getPosts() {
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"});
getPosts();
Asynchronous operation
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 getPosts() {
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"}, getPosts);
References:
http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/
https://houssein.me/javascript/2016/05/10/asynchronous-javascript-callbacks.html
http://callbackhell.com/
https://developer.mozilla.org/en-US/docs/Glossary/Callback_function
0 comments:
Post a Comment