2

Good morning all! I am having issues getting an axios response back from a different function. Specifically, I am consulting a service I created in a different website and have it return a database name. Currently, as I call the api directly with it's headers on Postman it works and the same when it is done inside the getDbName() function I created using axios, however when I try to return that response into another one, it prints out "undefined". It was my understanding that as long as the response => arrow functions are used, the call would await the response properly. Am I wrong on that assumption?

I've tried many different attempts of returning the variable. I investigated using the many links on SO below, but I still couldn't get it to work:

axios promise returns correct value in "axios.all" function, but is undefined in the "then" function

Axios prints value on console but returns undefined

GET request with axios returning undefined

[dbController.js]
import axios from 'axios';
import apiconfig from '../config/apiconfig';

function getDbName() {
  return axios({
    method: 'GET',
    url: `${apiconfig.cb_url}/api/DbToBeWorked`,
    headers: apiconfig.optionsHeaders,
  }).then(dbn => {
    console.log(dbn.data.db); //logs database name correctly
    return dbn.data.db;
  });
};

[routes.js]
import { Router } from 'express';

const routes = new Router();

routes.get('/api/test', (req, res) => {
  getDbName().then(dbn => {
    console.log(dbn) //this logs 'undefined'
    return res.status(200).json(dbn);
  });
});

The output should be dbn (database name) for both console.logs. At the moment, one returns the correct name and the other returns undefined.

  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Heretic Monkey Oct 13 '21 at 16:41

2 Answers2

1
const getDbName = function () {
 return new Promise((resolve, reject) => {
    axios({
        ///----
    })
        .then(response => {
            resolve({
                // Do something 
            })
        })
        .catch(err => {
            reject({
                // Do something
            })
        })
  })

}

routes.get('/api/test', async(req, res) => {
 try{
  await getDbName()
 }catch(error)
  /// error

});
Angels
  • 325
  • 4
  • 15
  • hi Angels, I changed it to return new promise using resolve and reject, but the result is the same from the routes function. It still logs undefined outside of the getDbName function. – Guilherme Simoes Oct 31 '19 at 15:49
  • I believe this will work unless you make some other kind of mistake. As long as your function returns something, It will bring the result in your API. – Angels Oct 31 '19 at 17:45
0

I am an idiot and forgot to export getDbName so that routes would read it. I had it being imported, but it wasn't being exported from the [controller.js]. The code I posted works fine.