一、 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 封装


黄万通
16 声望0 粉丝