es6异步之await和async异步

手上的项目写好的接口已经对接完了。最近闲下来了,上家公司的主管跟我提起了前端和node.js。node必定是以后前端的一项重要技术。这次不再看视频从基础开始了,直接看自己需要的东西。

说到异步就会想到promise,在es6中的await和async也是异步操作。

await 和 async是建立在 promise机制之上的。不能说有了await和async就不要promise。
async

用来表示函数是异步的,定义的函数会返回一个promise对象,可以使用then方法添加回调函数。
await

可以理解为是 async wait 的简写。await 必须出现在 async 函数内部,不能单独使用。
await 最主要的意图是用来等待 Promise 对象的状态被 resolved后才继续执行。(也可以不是Promise对象)
await 对于reject的处理将代码包裹在try{//代码}catch(err){}

下面是一段简单的示例

const wait1 = () => {
    return new Promise(resolve => {
        resolve(setTimeout(() => {
            console.log('第一个wait')
        },1000))
    })
}
const wait2 = () => {
    return new Promise(resolve => {
        resolve(setTimeout(() => {
            console.log('第二个wait')
        },2000))
    })
}
async function test() {
    const a = await wait1()
    const b = await wait2()
    console.log("end")
}
console.log("start")
test()

运行方式如下:

C:\Users\Administrator.SKY-20170401TQI\Desktop\IT\node.js\koa2>node server.js
start
end
第一个wait
第二个wait

wait1和wait2是定义好的异步函数。

2018/12/13更新

之前的定时器中定时器来没执行完毕就执行了end步骤,如果我要等定时器都跑完在执行end该怎么做呢?

wait1 () {
    return new Promise((resolve) => {
        setTimeout(function () {
            resolve()
            console.log('第一个等待')
        },1000)
    })
},
wait2 () {
    return new Promise((resolve) => {
        setTimeout(function () {
            resolve()
            console.log('第二个等待')
        },1500)
    })
},
AsyncWait () {
    var that = this
    async function a() {
        console.log('程序启动')
        await that.wait1 ()
        await that.wait2 ()
        console.log('程序结束')
    }
    a ()
},

这样打印出来的就是

程序启动
第一个等待
第二个等待
程序结束

之前的是纯粹的异步操作,当前更新的是等待每个异步执行完成之后才去执行下一个操作

主要还是根据不同的场景来选择使用

猜你喜欢

转载自blog.csdn.net/qq_40816649/article/details/84197756