Search code examples
node.jsapiserverasync-awaitkoa

ctx.body undefined in async/await function


I'm trying to return from my node server with koa to my angular front end the result of an api call. Here's my controller which require a npm module which provides access to their api. Await should wait for the result and than return, am I wrong? I did something similar in a previous project but I was asking data from a db. Why it is not working?

const color = require('colourlovers');

exports.getAllColors = async (ctx) => {
  ctx.res.body = await color.get('/color/FFFFFF', { format: 'json' }, (err, data) => {
    console.log(data);//<---here is logging the data
    return data;
  });
  console.log(ctx.res.body);//<---here is undefined
  ctx.status=200;
};

Solution

  • You can not await color.get because it uses callbacks instead of promises (well, you can await it, but it doesn't do what you'd expect). So to use await, you need to build the promise yourself:

    ctx.res.body = await new Promise((resolve, reject) => {
        color.get('/color/FFFFFF', { format: 'json' }, (err, data) => {
            if(err) reject(err);
            else resolve(data);
        });
    });
    

    Now it'll wait for the promise to be resolved or rejected.