async and await introduce

374 阅读2分钟

Legendary journey 1888

async和await

两者分别的意思,async:异步,await:等待.

程序运行有一个过程,以线程来分,多线程,单线程.async和await是es7出现的语法,没有async之前,是以回调函数来运行的。

async关键字设定函数需要异步处理,在需要异步转同步的函数添加await等待异步事件,以至于函数会同步执行。

我的历史记录

我曾经在js代码中想,我想要程序延迟几秒运行,然后怎么实现呢,我是找来几个方法去做的。

方法1

function sleep(ms){
  return new Promise((resolve)=>setTimeout(resolve,ms));
}
async function test(){
  var temple=await sleep(1000);
  console.log(1111)
  return temple
}
test();

sleep是异步执行,使用promise,当promise的进程执行完毕之后,temple才会继续运行下去,然后就会延迟打印数字了。

这是中规中矩的promise的用法。

方法2

// 利用循环
function sleep(d){
  for(var t = Date.now() ; Date.now()-t <= d ;)
  {
    continue;
  }
}

通过初始化的时间,程序是同步的,程序一只循环,当时间是没有到那个时间的时候,都会一直循环调用。

方法3

function* sleep(ms){
   yield new Promise(function(resolve,reject){
             console.log(111);
             setTimeout(resolve,ms);
        })  
}
sleep(500).next().value.then(()=>{
  console.log(11111)
})

es6的用法,yield迭代,和promise差不多。

方法4

var sleep = require('sleep');
var n=10;

sleep.sleep(n) //sleep for n seconds
sleep.msleep(n) //sleep for n miliseconds
sleep.usleep(n) //sleep for n microseconds (1 second is 1000000 microseconds)

我当时也使用node的的事件处理,有一个sleep的库。

同步

function promiseFun1 () {
	return new Promise((resolve)=>{
      		setTimeout(()=>{
          		resolve(1)
      		}, 2000)
            })
}
function promiseFun2 () {
	return new Promise((resolve)=>{
      		setTimeout(()=>{
          		resolve(2)
      		}, 2000)
            })
}
function promiseFun3 () {
	return new Promise((resolve)=>{
      		setTimeout(()=>{
          		resolve(3)
      		}, 2000)
            })
}
function promiseFun4 () {
	return new Promise((resolve)=>{
      		setTimeout(()=>{
          		resolve(4)
      		}, 1000)
            })
}
async function test() {
	const r1 = await promiseFun1(); 
    const r2 = await promiseFun2(); 
    console.log(r1,r2);
   	promiseFun3().then(console.log);
   	promiseFun4().then(console.log);
}
test()

浏览器按ctrl+shift+i终端跑一下代码,输出顺序是1 2,4,3。r1和r2是等待异步函数执行完毕再次运行下面的程序,而promiseFun3和promiseFun4是异步函数异步执行,执行完毕,才有promiseFun4的函数先打印。

简单的说,要程序的某一个函数运行完,数据也要得到完,那么就设置await进行同步,多个异步函数一起执行的。程序的函数运行完,但是其中的包含的函数可能多个函数异步执行,那么不需要await,用then进行异步操作即可。