无法解决对象中的promise

时间:2018-04-28 01:29:55

标签: javascript promise

我尝试在一个对象方法中获取文件并返回promise,然后在同一对象的另一个方法中使用此数据:

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);

正确地在getText方法中使用text.json中的console.log JSON。我的text.json是有效的json文件。我在控制台出错:

  

未捕获的TypeError:无法读取属性'然后'未定义的       在Object.fillText(translator.js:35)

在fillText方法中,

35行是.then((res) => {。我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

你从未从getText()返回任何内容。改变这个:

fetch('js/text.json')

到此:

return fetch('js/text.json')

此外,在then的第二个getText回调中使用Promise构造函数是多余的,您可以直接返回值:

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

默认情况下,它将被视为已解决的承诺。

答案 1 :(得分:1)

你忘了归还

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