0

I have the following axios call in my code. It should return a number from my database in the column slots. In the code below, the console log for the response shows the correct number, then I return it to process in another function, however when I try to do math with it, I get an NaN result!

I've even tried using parseInt and no luck there as well. Any advice?

function getCurrentSlotsAxios(group_id) {
   axios.get('group/' + group_id)
       .then( (response) => {
           console.log('getCurrentSlotsAxios ' + group_id +': ' + parseInt(response.data.slots)) //shows the correct # in console
           return parseInt(response.data.slots) //attempted parseInt in case it was returned as a string for some reason
       })
       .catch( function(error) {
           console.log(error)
           }
       )
  }

Then in another function:

let current_slots = getCurrentSlotsAxios(group_id)
console.log(current_slots + 1) // results in NaN whether I use parseInt or not :( 
movac
  • 1,576
  • 3
  • 21
  • 45
  • 2
    `getCurrentSlotsAxios` returns a Promise – Jaromanda X Sep 23 '19 at 10:00
  • If you log current_slots after running the function, what do you see? – amazonic Sep 23 '19 at 10:01
  • 3
    `getCurrentSlotsAxios ` returns `undefined` i.e. nothing – AZ_ Sep 23 '19 at 10:01
  • ahh you guys are right, logging current_slots returns undefined...how do I have it return the actual number? Why does it show the correct number when console logged within the axios call? – movac Sep 23 '19 at 10:06
  • @JaromandaX No. There is no return statement, so it does not return a promise. It returns `undefined`. – some Sep 23 '19 at 10:07
  • @Maribov See the link in the yellow box above your question. – Ivar Sep 23 '19 at 10:09
  • 2
    @Maribov When you call the function, it immediately returns `undefined` and you try to add 1 to that, and that will give you `NaN`. The axios call happen sometime in the future, and when that happens, it have the correct value. – some Sep 23 '19 at 10:09
  • @Maribov You could use [async/await](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await) to solve your problem. – some Sep 23 '19 at 10:12
  • 1
    sorry, I meant `axios.get` returns a Promise ... your function returns nothing – Jaromanda X Sep 23 '19 at 10:13

0 Answers0