JS callback 实现 asynchronous

模拟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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值