关于javascript:JavaScriptasync-await-和-Promise-的使用

async function test1() {
  // async 返回的都是 Promise
  return 1
}

async function test2() {
  // return 2
  return Promise.resolve(2)
}

const res1 = test1()
const res2 = test2()
console.log('res1', res1)
console.log('res2', res2)

async function test3() {
  const p3 = Promise.resolve(3)
  p3.then(data => {
    console.log('then p3', data)
  })
  // then 等价 await
  const data = await p3
  console.log('await p3', data)
}
test3()
// 
async function test4() {
  const data4 = await 4 // 等价 Promise.resolve(4)
  console.log('await data4', data4)
}
test4()
// 
async function test5() {
  const data5 = await test1() 
  console.log('await data5', data5)
}
test5()

async function test6() {
  const p6 = Promise.reject(6)
  // 无奈捕捉异样
  // const data6 = await p6
  // console.log('await p6', data6)
  try {
    const data6 = await p6 
    console.log('await p6', data6)
  } catch(e) {
    console.log('e', e)
  }
}
test6()

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理