async & await &promise

2022-07-06  本文已影响0人  江湖小盛

async

const getInfo = async () => {
  return 'hello world'
}
getInfo() // Promise {<fulfilled>: "hello world"}
const getInfo = async () => {
  return Promise.resolve('hello world')
}
getInfo()  // Promise {<fulfilled>: "hello world"}
const getInfo = async () => {
  return Promise.resolve('hello world')
}
getInfo().then(res => {
  console.log(res) // hello world
})
const getInfo = async () => {
  return Promise.reject('出错了')
}
getInfo().then(res => {
  console.log(res)
}).catch(err => {
  console.log(err) // 出错了
})

await

const getMsg1 = () => {
  return Promise.resolve('test1')
}

const getMsg2 = () => {
  return Promise.resolve('test2')
}
const resultMsg = async () => {
  const [p1, p2] = await Promise.all([getMsg1(), getMsg2()])
  console.log(p1, p2)
}
resultMsg()
console.log('我先执行')
执行结果:'我先执行' -> 'test1 test2'

错误处理

const getMsg1 = () => {
  return Promise.resolve('test1')
}

const getMsg2 = () => {
  return Promise.reject('出错了')
}
const resultMsg = async () => {
  try {
    const [p1, p2] = await Promise.all([getMsg1(), getMsg2()])
    if (p1 && p2) {
       console.log(p1, p2)
    }
  } catch (e) {
    console.log(e)
  }
}
resultMsg()

模拟接口

  // 模拟接口
  function request() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {

        const res = {
          code: 200,
          data: [{
            name: 'zhang',
            age: 10
          }]
        }

        if (res && res.code === 200) {
          resolve(res)
        } else {
          reject('请求失败')
        }
      }, 3000)
    })
  }

  // 请求接口
  const getInfo = async () => {
    try {
      let res = await request()
      if (res && res.code === 200) {
          console.log(res.data)
      }
    } catch (err) {
      console.log(err)
    }
  }

  getInfo()
上一篇下一篇

猜你喜欢

热点阅读