1

Hi i' m doing an axios request to get the image but response parametrs cannot be assigned to any kind of variable but i can read them in console.log Where I'm wrong?

 let string = null;

        axios.get('/images/0dace5ee-1be7-4d2c-a07fb03927096815')
            .then(res =>{
                 console.log(res.data) //returns the value of the binary
                 console.log(res.headers['content-type']);//returns the current type image/png
                 string = 'data:'+res.headers['content-type']+';base64,'+ btoa(res.data);
        })
        .catch(error => {
            console.log(error)
        })
        console.log(string)//returns null
WayneC
  • 5,569
  • 2
  • 32
  • 43
benn98
  • 125
  • 11
  • .get is asynchronous, so your console.log(string) function call fires before the promise is resolved. – jjjjjjjjjjjjjjjjjjjj Dec 12 '17 at 10:52
  • because it will be a async call, so put the `console.log(string)` inside `.then` it will print the proper value. Check this answer for more details [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) – Mayank Shukla Dec 12 '17 at 11:00

1 Answers1

1

console.log(string); should be inside the promise chain.

More on promises

Since they run asynchronously your console.log (outside the then chain) will run before the promise is done. So all your work that needs to run after the call must be inside the .then chain. or .catch for errors

let string = null;

        axios.get('/images/0dace5ee-1be7-4d2c-a07fb03927096815')
            .then(res =>{
                 console.log(res.data) //returns the value of the binary
                 console.log(res.headers['content-type']);//returns the current type image/png
                 string = 'data:'+res.headers['content-type']+';base64,'+ btoa(res.data);
                 // it's async so you should console.log in in .then promise chain.
                 console.log(string);             
        })
        .catch(error => {
            console.log(error)
        })
João Cunha
  • 9,929
  • 4
  • 40
  • 61