Make koa.js do something on load (not on request)

563 views Asked by At

I can use koajs middleware with app.use(function *() { ... }) But, how can I make koajs when the app is launched?

It is trivial to simply code anything in js before all actions, but what if I would like it to perform some async stuff before and outside the middlewares? For example, I might want to obtain a certain key with an API call to an external server, to store it into a variable and return it when I get any request.

1

There are 1 answers

0
gfpacheco On BEST ANSWER

As you said, you can simply put it outside any middleware and call app.listen() only when your task is done:

var koa = require('koa');
var app = koa();

// add all your middlewares

loadKeyOrSomethingAsync().then(function() {
    app.listen(3000);
});

This way your server will wait your async task to complete before start listening for requests.