空承诺在 ES6 中使用导入的类返回

Empty promise return in ES6 using an imported class

本文关键字:导入 返回 承诺 ES6      更新时间:2023-09-26

我有一个问题,为什么我的回复被返回并打印为未定义。

这是我的主要方法.js:

find() {
        return this.serviceFactory
            .createRequest()
            .withId(333)
            .sendAsGet().then(response => {
                console.log(response);
            });
    }

上面的控制台.log(响应)是我获得未定义响应的地方;

这是用作 this.serviceFactory 的导入类

export class ServiceFactory {
    constructor(http) {
        this.http = http;
        this.http.baseUrl = serviceUrlParts.baseUrl;
        this.endpoint = "";
        this.id = "";
    }
    createRequest() {
        return this;
    }
    withId(id) {
        this.id = id;
        return this;
    }
    setEndPoint(endpoint){
        this.endpoint = serviceUrlParts.baseUrl + endpoint;
    }
    sendAsGet() {
        return this.http.get(`${this.endpoint}/${this.id}`)
            .then(response => {
                this.parseJSONContent(response);
            }).catch(error => {
                console.log(error);
            });
    }
    parseJSONContent(response) {
        console.dir(JSON.parse(response.content));
        return JSON.parse(response.content);
    }
}

parseJSONContent 方法中的 console.dir(JSON.parse(response.content)) 正在打印出从 API 返回的正确对象。 在某个地方回到电话中,它正在丢失。 对正在发生的事情的错误的一些见解将不胜感激!

这里不返回值:

.then(response => {
    this.parseJSONContent(response);
})

将其更改为:

.then(response => {
    return this.parseJSONContent(response);
})

.then(response => this.parseJSONContent(response))