JS实现异步请求的四种方法对比

JS中通常实现浏览器和服务器的数据交互,那么异步操作是关键的一部分:

通常情况下,浏览器想服务器发送请求,服务器相应请求返回数据,浏览器执行异步操作。在这里使用定时函数模拟异步请求数据。

// 使用定时函数模拟异步请求:
// 方法一:使用回调函数
function doSomething(callback){
  setTimeout(function(){
    console.log('执行结束');
    let result = 4;
    callback(result);
  },100);
}

function callback(result){
  console.log('接收到结果为:'+result);
}

doSomething(callback);
doSomething((result)=>{console.log('接收到结果为:'+result)});


// 方法二:promise对象
function doSomething(){
  return new Promise(function(resolve){
    setTimeout(function(){
      console.log('执行结束');
      let result = 6;
      resolve(result);
    },100);
  });

}

doSomething().then(result=>{
  console.log('接收到结果为:'+result);
});


// 方法三:generator函数
function doSomething(){
  setTimeout(function(){
    let result = 6;
    it.next(result);
  },100);
}

function *gener(){
  var result = yield doSomething();
  console.log(result);
}

let it = gener();
it.next();

// 方法四:async(ES7)
function doSomething(){
  return new Promise(resolve=>{
    setTimeout(function(){
      let result = 6;
      resolve(result);
    },100);
  });

}

async function action(){
  let result = await doSomething();
  console.log(result);
}
action();

基本上,常用的主要是回调函数和promise对象。对于async是未来的方向,ES7使用范围将会增加。

猜你喜欢

转载自blog.csdn.net/weixin_41697143/article/details/82758886