0

I'm new in javascript, and found some issue with scope of the object/variable, I need your help to point out why my {endtoken:this.token} is blank, while console.log({rawToken:e.data}) is don't?

I found that understanding the scope of the variable bit confusing in JS compared to Python, Is there any good easy to read link to understand the concept?

My goal is to get all data from windows parent and Rest API when the component is created.

    var obj = {
        token: '',
        init: {},
        user: {}, 
        objInfo: {}
    }; 

var app = new Vue({
    el: '#app-4',
    data: obj, 
    created: function(){
        postRobot
        .send(window.parent, "loadingCall", false, {domain: domain})
        .catch(function (e) {
            console.log(e);
        });

        postRobot
        .send(window.parent, "tokenCall", {}, { domain: domain })
        .then(function (e) {
            this.token = e.data; // token 
            console.log({rawToken:e.data});
            console.log({token:this.token});
        })
        .catch(function (e) {
            console.log(e);
        });

        postRobot
        .send(window.parent, "initCall", {}, { domain: domain })
        .then((e)=>{
            this.init = e.data;
            console.log({rawInit:e.data});
            console.log({init:this.init});
        })
        .catch((e)=>{
            console.log(e.data);
        });

        console.log({endtoken:this.token}); // blank token
        console.log({endinit:this.init}); // blank object
    }
});

Regards,

Harris, 10th Grade GPS Jakarta

  • Because you try to access it before it becomes available. "then" should be understood literally, it designates that it's called sometime in future when a promised result is available. Also this is a mistake, `.then(function (e) { this.token = e.data;`. See https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback – Estus Flask Jul 25 '21 at 12:41

1 Answers1

0

this happens due to the asynchronous nature of javascript. you can read a good article about it right here

What happens in your code is that your last console.log statements (last ones in the file) are get executed before the then parts are.

what happens is:

  1. you are sending a request through your postRobot, (you don't know when the request will return an answer)
  2. you are "skipping" the then and catch parts and run the "last" console.logs
  3. you get your responses back and only when the response comes back, the then part gets executed

basically you are logging the data before it has arrived and was set in these variables and therefore the output of the log is the data initial state

this post has a similar case as yours

Liad
  • 789
  • 4
  • 10