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
  }
})
浏览器结果

控制台结果
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 深蓝海洋 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读