关于javascript:asynawait-的语法和使用

9次阅读

共计 1685 个字符,预计需要花费 5 分钟才能阅读完成。

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

正文完
 0