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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AC_greener/article/details/88398300

看一个最简单例子:

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

猜你喜欢

转载自blog.csdn.net/AC_greener/article/details/88398300