yxfanxiao / yxfanxiao.github.io

My Blog Space
3 stars 0 forks source link

ES7 async await #8

Open yxfanxiao opened 8 years ago

yxfanxiao commented 8 years ago

ES7 async/await

async 申明一个异步函数,此函数需要返回一个Promise对象。

await可以等待一个Promise对象resolve,并且拿到结果。

由于是ES7的特性,所以现在使用需要 require("babel-polyfill")

require("babel-polyfill")

async function continueLife() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log("continue 1s life here")
            resolve()
        }, 1000)
    })
}

async function testLife() {
    console.log("start: " + new Date())
    await fn()
    console.log(("end: " + new Date()))
}

testLife()

结果,1s续成。

start: Mon Feb 22 2016 18:04:32 GMT+0800 (中国标准时间)
continue 1s life here
end: Mon Feb 22 2016 18:04:33 GMT+0800 (中国标准时间)

以前的callback hell

a(b(c(d())))

现在可以优雅的解决

async function a() { return new Promise(...)} // b,c,d 同理

(async function {
    await a()
    const v = await b()
    await c(v)
    await d()
})()