tldr How can I set a class variable from within an Promise
I'm banging my head as I'm too stupid to use async/await
with javascript. There are of course plenty of examples and blog posts, but they are 'then'
inning the results only into console.log
, what I don't need.
My use case is very simple, I want to load translations from a json using fetch (if they haven't been loaded yet) and then return the translated value with a function translate
.
I thought if I use then
, then the execution is paused until the Promise
resolves or fails.
class Test {
constructor() {
}
/**
* Loads translations
*/
async _loadTranslations() {
console.log("Loading tanslations");
let response = await fetch('data.json');
let json = await response.json();
return json;
};
translate(key, language) {
if(!this.translation){
this._loadTranslations().then(data =>{
console.log("data is loaded!", data);
this.translation = data;});
}
return this.translations[language][key];
}
}
console.log("translation",new Test().translate("MEGA_MENU_CMD","de-DE"))
But it always logs translation undefined
.
I don't want something like
new Test()._loadTranslations().then(r => console.log("result",r))
as I want to use the translate function within templates and I don't want to use .then
in all of my templates.
Edit I don't see how I can use the fetch
to get data from an API and set it as the model of a class. The then
s and callback
s in my opinion do different things. Or how is the correct way to instantiate a class, load data from an API and then work with this data?
2nd edit:
In fact, I just want to create a TranslationMixin and load the translations once. Then in my page (I'm playing around with Polymer) I want to use return html '<div>${this.translate("de-De","propertyX"}<div>'
and that's why I don't want a Promise but just the plain string. In fact the translation should be loaded during construction and done. But as fetch
returns a Promise
I'm stuck with the Promise
and fail to get the value out (#sigh). So probably I stick just to regular XMLHttpRequest
...