【问题标题】:Cannot resolve promise in object无法解决对象中的承诺
【发布时间】:2018-10-08 20:45:26
【问题描述】:

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

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 文件。我在控制台中遇到错误:

未捕获的类型错误:无法读取未定义的属性“then” 在 Object.fillText (translator.js:35)

第 35 行是 fillText 方法中的.then((res) => {。我在这里做错了什么?

【问题讨论】:

  • 您需要在getText返回 fetch,以便getText 的消费者可以访问它。否则,getText() 返回undefinedgetText() { return fetch('js/text.json')
  • 你不需要在最后一个 then() 中创建一个新的承诺来解决响应。删除最后一个then() 部分并返回fetch().then()

标签: javascript promise


【解决方案1】:

您从未从getText() 返回任何东西。改变这个:

fetch('js/text.json')

到这里:

return fetch('js/text.json')

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

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

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

【讨论】:

    【解决方案2】:

    忘记退货了

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-18
      • 2019-05-09
      • 2019-07-21
      • 2018-05-28
      相关资源
      最近更新 更多