ES6:await和async的区别和使用

先看一个例子

      console.log(1);
      async function test() {
        console.log(2);
        await function () {
          setTimeout(()=>{
            console.log(3);
          })
        }
        console.log(4);
      };
      console.log(5);
      test();
      console.log(6);

输出结果:1,5,2,6,4

async

async确保了函数返回一个promise

  console.log(1);
  async function f () {
    console.log(2)
    return 'hello world!'
  }
  f().then(result=>{
    console.log(result);
  })
  console.log(3);
  //1,2,3,'hello,world'

await

await只能在async函数内部使用,await不能工作在顶级作用域
await可以让JavaScript进行等待,直到一个promise执行并返回它的结果,JavaScript才会继续往下执行。
使用举例子

  console.log(1);
  async function f () {
    console.log(2);
    let promise = new Promise((resolve, reject) => {
      console.log(3);
      setTimeout(() => {
        resolve('done!')
      }, 1000)
    })
    let result = await promise;
    console.log(result);//done
    return 5;
  }
  f().then(result=>{
    console.log(result);//5
  })
  console.log(6);
  // 1,2,3,6,[等待1秒],'done',5

错误处理

async function f() {
    let response = await fetch('http://no-such-url')
}
// f()变成了一个rejected的promise
f().catch(alert) // TypeError: failed to fetch

async function f() {
    throw new Error('Whoops!')
} 

有了async/await,我们很少需要写promise.then/catch,但是别忘了它们是基于promise的,

其他:如Promise.all

可以适当的和async和await公用,Promise.all能够同时等待很多任务。

在vue中的应用举例

methods: {
  updateMessage: async function () {
    this.message = 'updated'
    console.log(this.$el.textContent) // => '未更新'
    await this.$nextTick()
    console.log(this.$el.textContent) // => '已更新'
  }
}
  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值