AJAX and Weakmaps requests

Asked

Viewed 28 times

3

As I put into practice what I have learned so far about ES2015 with Babel. specifically about Weakmaps, I got into a problem that I don’t know why it happens and with that, I don’t know how to solve.

I have a Weakmap set to store information coming from an AJAX Request which is only triggered if this Weakmap has nothing stored.

I’ve come to this:

class User {

    constructor( id ) {

        id = Number( id );

        if( id <= 0 || isNaN( id ) ) {
            throw new TypeError( 'Invalid User ID' );
        }

        _id.set( this, id );
    }

    getID() {
        return _id.get( this );
    }

    getData() {

        let _this = this;

        if( _data.get( _this ) === undefined ) {

            _this.loadData().done( function( data ) {

                // JSON is indeed successfully loaded

                console.log( data );

                _data.set( _this, data );

                // WeakMap is indeed set correctly

                console.log( _data.get( _this ) );
            });
        }

        // But here it's undefined again!

        console.log( _data.get( _this ) );

        return _data.get( _this );
    }

    loadData() {

        return $.get({
            url: '/users/' + _id.get( this, data ),
        });
    }
}

let _id   = new WeakMap;
let _data = new WeakMap;

// ---------------

var user = new User( 1 );

console.log( user.getID(), user.getData() ); // 1 undefined

As far as I know Weakmap has been set correctly, so much so that the same is done with the user ID and this can be obtained normally, thus ruling out possible problems with the transcompiler.

But information coming from AJAX, even if it is coming from jquery.done() correctly, cannot be accessed outside of it.

The only way I could make it work was by setting async: false in the $.ajax, what I know is not right.

What am I doing wrong? Not knowing why I can’t even research the subject and try for myself.

2 answers

1

The question here is basically the same as this, or this. That is: ajax is asynchronous. That means that:

// pseudo código:
var x = 10;
ajax(function(){
    x = 20;
});
console.log(x); // dá 10

What happens is that ajax takes time to execute and even though it is very fast) the code will continue to run coming to console.log before ajax to be completed.

The solution to this is to call the console.log when the ajax has something to return. This can be done with callback, or with Promises.

The solution is, how did you find, do getData return a deferred object, type Promise:

user.getData().done(function(data){
    console.log( data );
})

0

I do not understand Javascript to the point of saying that this is the correct solution but I researched MUCH and read numerous answers both in the stack Overflowen like the Internet outside, which in an attempt to teach people to fish, ended up starving them with almost endless, complex answers or simply hiding the solution in the midst of so much information not so necessary.

To those of interest:

class User {

    constructor( id ) {

        id = Number( id );

        if( id <= 0 || isNaN( id ) ) {
            throw new TypeError( 'Invalid User ID' );
        }

        _id.set( this, id );
    }

    getID() {
        return _id.get( this );
    }

    getData() {

        if( _data.get( this ) === undefined ) {
            _data.set( this, this.loadData() );
        }

        return _data.get( this );
    }

    loadData() {
        return $.getJSON( CARD_LIST + '/player/' + _id.get( this ) );
    }
}

let _data = new WeakMap;

// ---------------

var user = new User( 1 );

user.getData().done( function( data ) {

    console.log( data );
})

It’s not what I had in mind initially, as I’ll have to use jQuery.done() every time I use a simple one getter (that in my opinion should bring the information ready for use) nor could explain the "how" or the 'whys".

It would be nice to know, of course, and if someone wants/can answer explaining in a didactic way it would be amazing, but for now I humbly hope that you help someone else who is trying to extract simple information from unfriendly responses/comments for those who don’t understand the subject as well as I do.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.