簡體   English   中英

無法解決對象中的承諾

[英]Cannot resolve promise in object

我試圖獲取文件並在對象的一種方法中返回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文件。 我在控制台中出錯:

Uncaught TypeError:無法讀取Object.fillText上未定義的屬性'then'(translator.js:35)

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

您從未從getText()返回任何東西。 更改此:

fetch('js/text.json')

對此:

return fetch('js/text.json')

此外,在第二個則使用無極構造函數then回調getText是多余的,您可以直接返回值:

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

默認情況下,它將被視為已解決的承諾。

你忘了退貨

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM