模拟post请求,synchronous时即使先create再get也可能get不到;
const posts=[
{title:'Post One', body:"this is post one"},
{title:'Post Two', body:"this is post two"}
]
function createPost(post){ //2秒后create post
setTimeout(function(){
posts.push(post);
},2000);
}
function getPosts(){
setTimeout(function(){ //1秒后get post
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(); //新craete的post并未被get到
使用callback,实现asynchronous;
将get函数作为参数传入create函数;
在create函数执行时执行get,防止因为异步而未get到信息;
const posts=[
{title:'Post One', body:"this is post one"},
{title:'Post Two', body:"this is post two"}
]
function createPost(post,callback){ //2秒后create post
setTimeout(function(){
posts.push(post);
callback();
},2000);
}
function getPosts(){
setTimeout(function(){ //1秒后get post
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);