0

Why this piece of code not working in laravel? I'm assigning Axios response to my global variable klines but when I try to console.log(klines) it gives me an empty array outside of it, when I try to console.log(klines) into Axios response it gives me data.

    var klines = [];

    let getKlineDataHistory = function(){
        let symbol = document.getElementById('symbol');
        let interval = document.getElementById('interval');

        axios({
            method:'post',
            url:'/get-klines',
            data:{
                symbol:symbol.getAttribute('value'),
                interval:interval.getAttribute('value')
            }
        }).then(function(response){

            klines = response.data;

        }).catch(function(error){

        });

    }
    
    
    getKlineDataHistory();
    
    console.log(klines)
  • 1
    The `then` function in your code, which sets the value of `klines`, doesn’t execute until much later than `console.log(klines)`. This is how async code behaves. Use await, or put your console.log code inside the then function also. See https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – James Aug 02 '23 at 12:19

0 Answers0