如何优雅地使用同步代码 处理异步流程

本文介绍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()

在实际项目中可以把定时器理解为我们调用的接口,有什么问题欢迎提问

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值