0

I am trying to write a web application that fetches data from GoogleMaps API. API response is correct in the then/catch block which is;

var axios = require('axios')

var config = {
    method: "get",
    url: httpRequest,
    header: { }
};

axios(config)
.then(function(response){
    console.log(JSON.stringify(response.data))
})
.catch(function(error){
    console.log(error)
})

in which the console.log works perfectly fine. I want to create a local object responseData and use that object outside of the then block. Here is an example;

var axios = require('axios')

let localObject ;

var config = {
    method: "get",
    url: httpRequest,
    header: { }
};

axios(config)
.then(function(response){
    console.log(JSON.stringify(response.data))
    localObject = response.data;
})
.catch(function(error){
    console.log(error)
})

console.log(JSON.stringify(localObject)) // Local Object undefined error

How can I assign localObject with response.data?

Lapaaci
  • 119
  • 7

1 Answers1

0

Your variable "localObject" is assigned with response.data value, but the line that logs this variable gets called before it's assigned, because JS is non blocking and what's inside "then" is running in the foreground, on the same thread as everything else, just later.

You can console.log(JSON.stringify(localObject)) inside "then" after the variable is assigned and then use it in the same scope.

var axios = require('axios')

let localObject ;

var config = {
    method: "get",
    url: httpRequest,
    header: { }
};

axios(config)
.then(function(response){
    console.log(JSON.stringify(response.data))
    localObject = response.data;
}).then(function(response){
// Use localObject variable here it will be assigned
})
.catch(function(error){
    console.log(error)
})

console.log(JSON.stringify(localObject)) // Local Object undefined error

Or use async, await like this

function async axios(){

var axios = require('axios')

var config = {
    method: "get",
    url: httpRequest,
    header: { }
};

let localObject =await JSON.stringify(axios(config)
)}
  • "*what's inside "then" is running […] in background.*" - not quite. It's running in the foreground, on the same thread as everything else, just later. – Bergi Mar 07 '23 at 13:20