I'm trying to fetch file and return promise in one method of object and then use this data inside another method of same object:
const translator = {
currentLanguage: '',
getText() {
fetch('js/text.json')
.then(res => res.json())
.then(res => {
console.log(res);
return new Promise((resolve) => {
resolve(res);
});
});
},
fillText(lang) {
this.getText()
.then((res) => {
console.log('in fill text: ');
console.log(res);
});
},
};
translator.checkLanguage();
translator.fillText(translator.currentLanguage);
It console.log JSON from text.json in getText method correctly. My text.json is valid json file. I got error in console:
Uncaught TypeError: Cannot read property 'then' of undefined at Object.fillText (translator.js:35)
35 line is .then((res) => { in fillText method. What I'm doing wrong here?
fetchingetTextso that it's accessible to consumers ofgetText. Otherwise,getText()returnsundefined.getText() { return fetch('js/text.json')- CertainPerformancethen()just to resolve the response. Remove the lastthen()part and return thefetch().then()- Patrick Evans