【问题标题】:How to return the response value to the caller function如何将响应值返回给调用者函数
【发布时间】:2019-02-08 22:06:21
【问题描述】:

我正在调用另一个类中的一个函数,其中包含一个 API 请求。我想将 API 请求的响应返回给我调用函数的类。但是 Console.log 会写出“Promise {pending}”。

    let test: Object = Utility.getManager(this.props.graphClient);
    console.log(test);

这里我用一个参数调用类“Utility”中的函数“getManager”。

public static async getManager(Client: MSGraphClient): Promise<Object> {
    return await Client
        .api("/me/manager")
        .version("v1.0")
        .get(async (error, response: any, rawResponse?: any): Promise<any> => {
            // handle the response
            console.log(response);
            return await response;
        });
}

在这里,我尝试将 API 请求的响应发送回以保存在“测试”中。

【问题讨论】:

    标签: reactjs typescript sharepoint spfx


    【解决方案1】:

    getManager 是一个异步函数,当你调用它时你会得到一个承诺(就像所有异步函数一样)。

    如果你想记录结果,你必须:

    let test: Object = await Utility.getManager(this.props.graphClient);
    console.log(test);
    

    【讨论】:

    • 那行不通。问题是 console.log(test) 在另一个类中的 Console.log(response) 之前写出。所以它不会等待返回。
    • 您能否澄清console.log 中的哪一个正在打印“Promise {pending}”、testresponse?我怀疑console.log(response) 正在打印出“Promise {pending}”,因为您在 之后写了 await response
    • console.log(test);正在打印“Promise {pending}”。 Console.log(响应);从 API 请求中打印出正确的响应。
    猜你喜欢
    • 2011-07-26
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    相关资源
    最近更新 更多