【问题标题】:'Unhandled Promise rejection:', 'Cannot read properties of undefined (reading 'then')''未处理的承诺拒绝:','无法读取未定义的属性(读取'then')'
【发布时间】:2021-08-27 17:01:18
【问题描述】:

我有这个错误:

'Unhandled Promise rejection:', 'Cannot read properties of undefined (reading 'then')', '; Zone:', 'ProxyZone', '; Task:', 'jasmine.onComplete', '; Value:', TypeError: Cannot read properties of undefined (reading 'then')
TypeError: Cannot read properties of undefined (reading 'then')

这是我的.ts 文件:

getPillars = async (): Promise<void> => {

        if (localStorage.getItem('pillars')) {
            this.pillars = JSON.parse(localStorage.getItem('pillars'));
            return;
        }

        let items = await this.api.send('Categories', 'get', filter ? { filter: filter } : {}).then((res: { data: any[], count: number }) => {
            return res.data.map(el => {
                return { id: el.id, name: el.name, type: 'Categories' }
            });
        });
        localStorage.setItem('pillars', JSON.stringify(items));

        this.pillars = items;
    }

还有我的测试文件:

describe('getPillars()', () => {
    it('Should validate the session success', () => {
        let spy1 = spyOn(apiService, 'send').and.returnValue(Promise.resolve(of('pillars')));

        component.getPillars();

        expect(spy1).toHaveBeenCalled();
      });
  });

【问题讨论】:

    标签: angular typescript karma-jasmine


    【解决方案1】:
    let items = await this.api.send('Categories', 'get', filter ? { filter: filter } : {}).then((res: { data: any[], count: number }) => {
                return res.data.map(el => {
                    return { id: el.id, name: el.name, type: 'Categories' }
                });
            });
    

    在这里等待从 send 返回的承诺

    但在稍后的测试中,您返回一个可解析为另一个 Promise 的 Promise。

    你必须让它只是解析为一些实际值

    let spy1 = spyOn(apiService, 'send').and.returnValue(Promise.resolve('pillars'));
    

    【讨论】:

    • 你能举个例子说明我应该如何解决这个承诺吗?
    • 您尝试过我发布的答案吗?提供的答案有什么问题?
    • 对不起,我错了,你的回答很好
    【解决方案2】:

    对于有类似问题但无法通过接受的答案解决的人: 我错误地导入了库。检查您正在使用的库,看看他们建议您如何导入它。

    import openpgp from 'openpgp';
    // Throws unhandled promise rejection.
    const {notImportant} = await openpgp.readKey({...}); 
    
    import * as openpgp from 'openpgp';
    
    // Executes successfully.
    const {notImportant} = await openpgp.readKey({...});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-12
      • 2020-07-30
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-11
      • 2017-05-29
      相关资源
      最近更新 更多