0
votes

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?

2
You need to return the fetch in getText so that it's accessible to consumers of getText. Otherwise, getText() returns undefined. getText() { return fetch('js/text.json') - CertainPerformance
You dont need to create a new promise inside the last then() just to resolve the response. Remove the last then() part and return the fetch().then() - Patrick Evans

2 Answers

2
votes

You never returned anything from getText(). Change this:

fetch('js/text.json')

to this:

return fetch('js/text.json')

Also, using the Promise constructor in the second then callback of getText is redundant, you can directly return the value:

.then(res => {
  console.log(res);
  return res;
});

It will, by default, be treated as a resolved promise.

1
votes

you forgot to return it

  getText() {
       return fetch('js/text.json')
            .then(res => res.json())
            .then(res => {
                console.log(res);
                return new Promise((resolve) => {
                    resolve(res);
                });
            });
    }