How to generate a slow response using koa?

Member

by kadin , in category: Javascript , 8 months ago

How to generate a slow response using koa?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jasen , 8 months ago

@kadin 

To generate a slow response using Koa, you can use a middleware function that delays the response by a certain amount of time. Here's an example of how you can achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
const Koa = require('koa');
const app = new Koa();

// Middleware function to delay response
app.use(async (ctx, next) => {
  // Delay response by 2 seconds
  await new Promise(resolve => setTimeout(resolve, 2000));
  await next();
});

// Route handler
app.use(ctx => {
  ctx.body = 'Slow response generated!';
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});


In this example, the middleware function delays the response by 2 seconds using setTimeout(). When you make a request to the server, it will take 2 seconds before you receive a response with the message "Slow response generated!". You can customize the delay time by changing the value in the setTimeout() function.