Search code examples
koa

koa js async await not working when used with ajax and promise


I'm using koa as a rest backend but I can't get the routing and request/response to work properly, when the URL is called using axios the promise is failing.

server.js

const route = require('koa-route');
const serve = require('koa-static');
const Koa = require('koa');
const app = new Koa();
const path = require('path');
const bodyParser = require('koa-bodyparser');
const Datastore = require('nedb'),
      db = new Datastore({
          filename: __dirname +'/storage.db' ,
          autoload: true
      });
// something 
app.use(bodyParser());

app.use(serve(__dirname + '/dist'));

app.use(route.get('/api/projects', async function (next) {
    let projects = [];
    await db.find({}, function (err, docs) {
        projects = docs;
    });

    this.body = projects;
}));

const PORT = process.argv[2] || process.env.PORT || 3000;
app.listen(3000);

when I make a request to /api/projects using axios I get and empty array

from my package.json

"scripts": {
    "start": "nodemon server.js --exec babel-node --presets es2015,stage-2"
  },

Solution

  • You're mixing promises with callbacks, which is most likely causing your problems.

    Stick to using promises:

    app.use(route.get('/api/projects', async function (next) {
      let projects = await db.find({});
      this.body = projects;
    }));