一、 async 函数

  • 函数的返回值为 promise 对象
  • promise 对象的后果由 async 函数执行的返回值决定
async function fn() {  // return 1 返回一个胜利的promise,值为 1  // throw 2 返回一个失败的promise,值为 2  // return Promise.reject(3) 返回一个失败的promise,值为 3  return Promise.resolve(4) // 返回一个胜利的promise,值为 4}const result = fn()console.log(result)

二、 await 表达式

  • await 右侧的表达式个别为 promise 对象, 但也能够是其它的值
  • 如果表达式是 promise 对象, await 返回的是 promise 胜利的值
  • 如果表达式是其它值, 间接将此值作为 await 的返回值
// 先定义一个fn1函数,它返回一个promise对象function fn1() {  return new Promise((resolve, reject) => {    // 应用定时器来提早promise的返回后果    setTimeout(() => {      resolve(6)    }, 2000)  })}// async函数会立刻执行完结返回一个pending状态的promise对象async function fn2() {  /*    await前面的代码会放入then()的胜利回调中执行的      const result = await fn3()      console.log(result)      相当于      fn3().then(result=>{         console.log(result)      })  */  const result = await fn3()  console.log(result)}

三、留神:

  • await 必须写在 async 函数中, 但 async 函数中能够没有 await
  • 如果 await 的 promise 失败了, 就会抛出异样, 须要通过 try...catch 来捕捉解决
async function fn1() {  throw 6}async function fn2() {  try {    // 应用try...catch来解决await后的promise的失败    const result = await fn1()    console.log('fn1 result=', result)  } catch (error) {    console.log('error', error)  }}fn2()

四、async/await、promise、ajax 联合应用

// ajax函数接管申请地址function ajax(url) {  // 返回一个promise对象  return new Promise((resolve, reject) => {    // 创立ajax对象    const xhr = new XMLHttpRequest()    // 监听xhr状态扭转    xhr.onreadystatechange = function () {      // 状态为4示意数据全副申请回来了      if (xhr.readyState === 4) {        // 状态在200-300之间示意胜利        if (xhr.status >= 200 && xhr.status < 300) {          // 执行resolve函数,并保留申请过去的数据,封装到data属性中          resolve({ data: xhr.responseText || xhr.responseXML })        } else {          // 执行reject函数          reject({ status: xhr.status, msg: '申请失败咯!' })        }      }    }    // 发送申请    xhr.open('get', url)    // 发送    xhr.send()  })}// 测试函数async function test() {  // await表达式必须写在async函数中  const res = await ajax('http://localhost:3000/test_get?name=kobe&age=42')  console.log(res) // {data: "{"msg":"申请胜利!","data":{"name":"kobe","age":"42"},"status":1}"}}test()

相干文章

手写 Promise
原生 ajax 封装