-1

Can anyone tell me how I can use var dataTitle outside of axios?

express = require('express') / 
const bodyParser = require('body-parser')
const axios = require('axios');
var randomInt = require('random-int');
const URL = 'url';
var randomNumber = randomInt(11)
axios.get(URL + randomNumber)
.then(function (response) {
var dataTitle = response.data.question;
console.log(dataTitle)
})
.catch(function (error) {
console.log(error);
});
SherylHohman
  • 16,580
  • 17
  • 88
  • 94
  • 1
    See https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call, and dozens of other similar posts. – jonrsharpe Feb 25 '19 at 17:57
  • 2
    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) – adiga Feb 25 '19 at 18:06
  • Axios is an asynchronous function call. Look up how to use promises or synch/await. Comments above link to two such existing Answers. Remember the format of StackOverflow strives to remove or proven duplicate answers and duplicate questions. You can read more about this in the SO help center, linked to at the top of every page. Understandably, a new user may not intuitively know to search for `asynchronous`, `promises`, or `asynch/await` when trying to understand `axios`. This is a great use case for responding via the comment (not answer) section for "how to use synch function xxx" questions. – SherylHohman May 12 '22 at 19:40

2 Answers2

0

It seems your question is about variables scope in JavaScript. You cannot use a variable outside of the function which is declared inside of the function. So, you have to declare it before than axios and use it in the axios as below:

express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
var randomInt = require('random-int');
const URL = 'url';
var randomNumber = randomInt(11);

var dataTitle;

axios.get(URL + randomNumber)
.then(function (response) {
     dataTitle = response.data.question;
     console.log(dataTitle)
})
.catch(function (error) {
     console.log(error);
});
Pouya Jabbarisani
  • 1,084
  • 3
  • 16
  • 29
0

Adding on top of Pouya Jabbarisani's answer, Since axios.get returns a promise and has asynchronous behavior, console.log(dataTitle) outside of function will still result in undefined.

In order to get the real value, use await axios.get(...).
Also, you need to make the wrapping function async.

SherylHohman
  • 16,580
  • 17
  • 88
  • 94