这两天试了下koa2,之前用express回调之后渲染页面的方式出错了,在koa2上执行流程不对,说白了就是代码的执行顺序错了,然后就上网找资料,认真的看了下文档终于搞明白了async+await配合promise的用法!!!! 不多说直接上码吧......

router.get('/', async function (ctx,next) {
    ctx.state = {
    title: 'title'
  };
  function timeout(ms) {
    console.log("111");
    return new Promise((resolve) => {
    setTimeout(resolve, ms);
    });
  }

  await timeout(1000).then(() => {
    console.log('222');
 });

 console.log("333");
 ctx.body=ctx;
});

 

代码执行结果

111
222
333

这个代码看懂了其实就懂了koa2的async+await配合promise的用法了……

相关文章:

  • 2022-12-23
  • 2021-07-20
  • 2021-07-23
  • 2021-12-02
  • 2021-04-20
  • 2021-09-19
  • 2021-12-28
  • 2021-12-17
猜你喜欢
  • 2021-12-05
  • 2020-01-11
  • 2022-12-23
  • 2022-02-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案