登录
登录 注册新账号
注册
已有账号登录

问题描述

使用koa, koa-router, 如何让其返回数据的时候延迟一秒?

问题出现的环境背景及自己尝试过哪些方法

按照网上的代码,似乎没问题

page.get('/test',
  async (ctx, next) => {
    ctx.body = { data: 'xxx' };
    console.log(1)
    await next();
    console.log(1);
  },
  async (ctx, next) => {
    console.log(2);
    await next();
    console.log(2);
  },
  ctx => {
    console.log(3)
  }
)

输出

1
2
3
2
1
// 数据返回

但是一旦使用 setTimeout 将不按照理想情况执行

page.get('/open_city',
  async (ctx, next) => {
    console.log(123)
    await next();
    console.log(789)
    ctx.body = 'hello';
  },
  (ctx, next) => {
    setTimeout(() => {
      console.log(456)
    }, 1000)
  }
)

输出

123
789
// 789后就会将数据返回,然后才会输出456
456

浏览器中会将setTimeout加入异步队列,node中也是如此?

如题,百思不得解。

1 个回答

不是async函数你让node怎么异步执行?
这需求简单就是写个异步延时函数

async function delayer(time = 2000) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, time);
  });
}

在你需要延时的路由中加上

async (ctx, next) => {
  await delayer(1000);
  await next();
  ctx.body = 'hello';
},
撰写答案