While I was putting into practice what I have learned so far about the ES2015 with Babel. specifically on WeakMaps, I came up with a problem that I do not know why it happens and I do not know how to solve it.
I have a WeakMap set to store information coming from an AJAX Request which is only triggered if that WeakMap has nothing stored.
I came 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 defined correctly, so much so that it is done with the user ID and can be obtained normally, thus ruling out possible problems with transcompiler .
But information that AJAX comes with, even though it is coming correctly inside jquery.done () can not be accessed outside of it.
The only way I could make it work was by setting async: false
to $.ajax
, which I know is not right.
What am I doing wrong? Without knowing why I can not even research on the subject and try for myself.