本文介绍Async 和Await的用法和原理
1 经过了Generator的过渡之后,异步代码同步化的需求逐渐成为了主流需求,这个过程在ES7当中得到
了提案,并在ES8中得到了实现,提案中定义了全新的异步控制流程
2 async 基础用法 看下面这段代码
async function test(){
console.log(3)
var a = await 4
console.log(a)
return 1 }
console.log(1)
test()
console.log(2)
它的输出顺序是1,3,2,4
3 async修饰的函数会被解释成Promise对象,翻译成如下结构:
console.log(1)
new Promise(function(resolve){
console.log(3)
resolve(4)
}).then(function(a){
console.log(a)
})
console.log(2)
4 最终该怎么处理异步流程呢 看以下代码
async function test(){
var res1 = await new Promise(function(resolve){
setTimeout(function(){
resolve('第⼀秒运⾏')
},1000)
})
console.log(res1)
var res2 = await new Promise(function(resolve){
setTimeout(function(){
resolve('第⼆秒运⾏')
},1000)
})
console.log(res2)
var res3 = await new Promise(function(resolve){
setTimeout(function(){
resolve('第三秒运⾏')
},1000)
})
console.log(res3) }
test()
在实际项目中可以把定时器理解为我们调用的接口,有什么问题欢迎提问