0

Hi I am trying to use an async function to return the response from login

The problem is that res.json is returned before it contains the reponse

const routes = require('express').Router();
const request = require('request');
const bodyParser = require("body-parser");
routes.use(bodyParser.json());
routes.use(
  bodyParser.urlencoded({
    extended: true
  })
);


routes.post('/login', async function (req, res) {

  let options = {
    form: {
      username: req.body.username,
      password: req.body.password
    }
  };

  var data = await request.post(
    req.url,
    options,
    await function (error, response, body) {
      if (error) {
        console.log(error);
      }

      // The data I want 
      return response;
    }
  )

  //This returns before it includes response
  res.json(data);

});

module.exports = routes;

Any ideas ?

Matti
  • 495
  • 6
  • 21
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – CertainPerformance Dec 13 '18 at 08:54
  • 2
    You can't use `await` on something that's not a `Promise`. Callback-based functions aren't Promises. – CertainPerformance Dec 13 '18 at 08:55

1 Answers1

0

You should use request-promise. Async-await only works with promises so you have to first convert request library into promisified form. Use below npm module for promisified version of request library.

https://www.npmjs.com/package/request-promise

Sanket
  • 945
  • 11
  • 24