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.