【发布时间】: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()返回undefined。getText() { return fetch('js/text.json') -
你不需要在最后一个
then()中创建一个新的承诺来解决响应。删除最后一个then()部分并返回fetch().then()
标签: javascript promise