【问题标题】:Function returning a Promise but I need a string [duplicate]返回 Promise 的函数,但我需要一个字符串 [重复]
【发布时间】:2021-03-27 04:24:31
【问题描述】:

我正在尝试从我的 API 调用中获取数据,但使用的是 Promise。

interface SomeType {
    status: string;
    other?: string; // not used - delete
}

indexStatus(indexName: string): string {
    // this.content = {};
    const returnedPromise = this.indexStatusCall(indexName)
        .then(returnData => {
            this.content = returnData;
            return returnData;
        });
    this.content = returnedPromise;
    console.log("----this.content: ", returnedPromise);
    return returnedPromise[0];
}

indexStatusCall(indexName: string): Promise < SomeType > {
    return this.http.fetch('http:API-PATH/indices/' + indexNameReplaced + '?format=json&h=status')
        .then(response => response.json())
        .then(data => {
            return data;
        });
}

这是 console.log 显示的内容

如何获得我的“状态”值?

【问题讨论】:

    标签: javascript api promise


    【解决方案1】:

    您需要等待承诺解决,然后才能访问结果。所以你的indexStatus 不能返回string,它必须返回Promise&lt;string&gt;。这也是您在console.log 中看到承诺的原因。

    使用异步/等待

    async indexStatus(indexName: string): Promise<string> {
        const data = await this.indexStatusCall(indexName);
        this.content = data;
        console.log("content", this.content);
        return data.status;
    }
    

    通过链接承诺

    indexStatus(indexName: string): Promise<string> {
        return this.indexStatusCall(indexName)
           .then(data => {
              this.content = data;
              console.log("content", this.content);
              return data.status;
           });
    }
    

    有关 Promises 的更多信息,MDN 提供了一些关于 Promises 工作原理的精彩教程。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

    【讨论】:

      猜你喜欢
      • 2020-11-02
      • 1970-01-01
      • 2018-02-05
      • 2020-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-08
      • 1970-01-01
      相关资源
      最近更新 更多