1

I've a problem with a return data from an async function located in Controller file.
I would to get my data in "let data", but it is undefined, I can't understand where is my error..
(of course in my concept of async functions :) )

Here my example:

// index.js
const DataController = require('../controllers/DataController');

router.get('/test', function (req, res, next) {

  let data = DataController.getData().then((resp) => {
    console.log(resp); // <-------- here is undefined

  });
});

// DataController.js
const axios = require('axios').default;
exports.getData = async function getData() {
        return axios.get("https://it.lipsum.com/")
            .then((response) => {
                // console.log(response)
                return response;
            })
            .catch(function (error) {
                // handle error
                console.log(error);
            })
            .then(function () {
                // always executed
            });
    }
Liam
  • 27,717
  • 28
  • 128
  • 190
Mariano
  • 473
  • 3
  • 12
  • 1
    Does this answer your question? [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) – Liam May 11 '21 at 13:57
  • 1
    `.then(function () { // always executed });` what is the code here? – VLAZ May 11 '21 at 13:57
  • Don't mix promises and async/await, use one or the other – Liam May 11 '21 at 13:58
  • @VLAZ an example of HTTP call from Axios documentation, the code was structured as a paste – Mariano May 11 '21 at 13:58
  • and the moral of that story is don't just cut and paste code you don't understand.... – Liam May 11 '21 at 13:59
  • 2
    This should simply be: `const response = await axios.get("https://it.lipsum.com/");` – Liam May 11 '21 at 14:00
  • 3
    @RogerAI well, that is the problem. If you have `promise.then().then()` the *second* `.then()` gets its value from the return of the previous `.then()`. So, if you have a `.then()` that doesn't return anything before yours, you get `undefined`. – VLAZ May 11 '21 at 14:01

2 Answers2

0

You need to return the data from the then call.

// DataController.js
const axios = require('axios').default;
exports.getData = async function getData() {
        return axios.get("https://it.lipsum.com/")
            .then((response) => {
                // console.log(response)
                return response;
            })
            .catch(function (error) {
                // handle error
                console.log(error);
            })
            .then(function (res) {
                // always executed
                return res;
            });
    }

The way it works that the Promise always returns the last value .then call returned, so your last .then call was returning then undefined.

Small note about let data = because the call is async you will see Promise not the data the promise will resolve to. You can use async/await syntax in the following way.

router.get('/test', async function (req, res, next) {

  let data = await  DataController.getData();
});
Ayzrian
  • 2,279
  • 1
  • 7
  • 14
  • There is no point in returning the same result twice – Liam May 11 '21 at 14:09
  • i was already tried this solution, but not working. I've used the @Liam const resp = axios.get(); and in first page .then( (resp) => console.log(resp) ); That work like a charm – Mariano May 11 '21 at 14:11
  • Yep, there is no point. I just describe the problem with the current code, and why this does not work. – Ayzrian May 11 '21 at 14:11
0

Refactor your files like this:

index.js

// index.js
const { getData } = require('../controllers/DataController');

router.get('/test', async (req, res, next) => {
  try {
    let data = await getData();
    console.log(data);
    return res.status(200).json(data);
  } catch (error) {
    console.log('ERROR: ', error);
    return res.status(400).json({
      success: false,
      error
    });
  }
});

DataController.js

const axios = require('axios').default;

const getData = async () => {
  try {
    let response = await axios({
      method: 'get',
      url: "https://it.lipsum.com/"
    });
    return response
  } catch (error) {
    return error;
  }
}

module.exports = { getData };
NeNaD
  • 18,172
  • 8
  • 47
  • 89