Koa2 異步async

1:模擬異步示例 routes/index.js
示例一:

router.get('/testAsync', async (ctx) => {
  global.console.log('start', new Date().getTime())
  const a = await new Promise((resolve, reject) => {
    setTimeout(function () {
      global.console.log('async a', new Date().getTime())
      resolve('a')
    }, 1000)
  })
  ctx.body = {
    a
  }
})

示例二:

router.get('/testAsync', async (ctx) => {
  global.console.log('start', new Date().getTime())
  const a = await new Promise((resolve, reject) => {
    setTimeout(function () {
      global.console.log('async a', new Date().getTime())
      resolve('a')
    }, 1000)
  })
  const c = await new Promise((resolve, reject) => {
    setTimeout(function () {
      global.console.log('async c', new Date().getTime())
      resolve('c')
    }, 1000)
  })
  const b = await '12'
  ctx.body = {
    a,
    b,
    c
  }
})
瀏覽器結果

控制檯結果
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章