【JavaScript】 异步的终极方案async,await

看一个最简单例子:

function x() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('hello js')
    }, 3000)
  })
}
async function test() {
  let n = await x()
  console.log(n)
  console.log('hello world')
}
test()

在这里插入图片描述
await后面必须跟一个返回promise的函数
这个代码块必须用async关键字声明

那如何捕捉promise里面失败呢?
用 try catch

function x() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject('出错啦')
    }, 3000)
  })
}
async function test() {
  try {
    let n = await x()
    console.log(n)
  } catch(err) {
    console.log(err)
  }
 
  console.log('hello world')
}
test()

在这里插入图片描述
那么如何在async函数里面使用多个异步呢?还是要用到promise

function x() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('hello')
    }, 3000)
  })
}

async function test() {
  try {
    let n = await Promise.all([x(), x()])
    console.log(n)
  } catch(err) {
    console.log(err)
  }
 
  console.log('hello world')
}
test()

在这里插入图片描述
总结:
1,使用async function声明一个一步函数
2,await关键字后面跟一个promise函数
3,await 关键字仅仅在 async function中有效
4,这个async function返回的也是一个promise

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值