无法解决对象中的承诺 [英] Cannot resolve promise in object

查看:43
本文介绍了无法解决对象中的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

It console.log JSON from text.json in getText method correctly. My text.json is valid json file. I got error in console:

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

Uncaught TypeError: Cannot read property 'then' of undefined at Object.fillText (translator.js:35)

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

35 line is .then((res) => { in fillText method. What I'm doing wrong here?

推荐答案

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

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

fetch('js/text.json')

为此:

return fetch('js/text.json')

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

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.

这篇关于无法解决对象中的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆