【问题标题】:Async function returns [object Promise] instead of the real value异步函数返回 [object Promise] 而不是实际值
【发布时间】:2019-02-26 17:47:05
【问题描述】:

我对 ReactJS 很陌生。

异步函数的返回值有问题

当我打电话时

const result = this.getFieldsAPI();

结果值为 [object Promise]

我从 console.log("result : " + result);

中看到 [object Promise]
getFieldsAPI = async() => {
    let currentChromosome = "";
    switch (this.state.chromosome) {
      case "Autosom":
        currentChromosome = "/getlocusautosomalkit/";
        break;
      case "Y_STRs":
        currentChromosome = "/getlocusykit/";
        break;
      case "X_STRs":
        currentChromosome = "/getlocusxkit/";
        break;
      default:
        currentChromosome = "";
    }
    let result = [];
    await Axios.get(API_URL + currentChromosome + this.state.currentKit).then((Response) => {
      Response.data.map((locus) => {
        result.push(locus);
      });
    })
    return "result";
  }

  // To generate mock Form.Item
  getFields() {
    const count = this.state.expand ? 10 : 6;
    const { getFieldDecorator } = this.props.form;
    const children = [];
    const result = this.getFieldsAPI();
    console.log("result : " + result);
    for (let i = 0; i < 10; i++) {
      children.push(
        <Col span={8} key={i} style={{ display: i < count ? 'block' : 'none' }}>
          <Form.Item label={`Field ${i}`}>
            {getFieldDecorator(`field-${i}`, {
              rules: [{
                required: true,
                message: 'Input something!',
              }],
            })(
              <Input placeholder="placeholder" />
            )}
          </Form.Item>
        </Col>
      );
    }
    return children;
  }

【问题讨论】:

  • 如果你想得到真正的返回值,使用const result = await this.getFieldsAPI();
  • 那么,你是说异步函数正在返回一个承诺?我认为这没有问题。他们就是这样做的。
  • 但是如果我在 getField() 前面添加了 async 就会抛出错误。
  • 我认为您的远程呼叫只是在一个不应该出现的地方。这不是您通常希望在每次渲染发生时都运行的东西。

标签: javascript reactjs


【解决方案1】:

您无需等待result 的值,因此您只是得到了一个未实现的承诺。如果你改变了

const result = this.getFieldsAPI();

const result = await this.getFieldsAPI();

你会得到你所追求的。您还需要使 getFields() 异步。

【讨论】:

  • 如果我将 getField() 设为异步。它会抛出错误。 对象作为 React 子级无效(找到:[object Promise])。如果您打算渲染一组子项,请改用数组。
【解决方案2】:

异步函数总是返回一个Promise。承诺可能会被解决或拒绝。你可以通过以下方式处理 Promise:

  1. 使用then
this.getFieldsAPI.then((value) => {
  // code on success
}, (errorReason) => {
  // code on error
});
  1. 使用await:
try { 
  const result = await this.getFieldsAPI();
} catch(errorReason) { 
  // code on error
}

您可以选择最适合您的。我个人更喜欢选项 2,这似乎不那么令人困惑。

【讨论】:

  • ...但感谢您提供选项 1,它更适合我的情况
【解决方案3】:

要获得有效响应,您应该稍微调整一下代码,因为目前您返回的是字符串“result”,而不是您的承诺中的数组。

在您的 getFieldsApi 方法中,您可以执行以下操作:

...
Response = await Axios.get(API_URL + currentChromosome + this.state.currentKit);
return Response.data.map((locus) => locus);

你会这样称呼它:

const result = await this.getFieldsApi();

【讨论】:

  • 如果我将 getField() 设为异步。它会抛出错误。 对象作为 React 子级无效(找到:[object Promise])。如果您打算渲染一组子项,请改用数组。 还有其他方法可以实现它并将 getField() 保持为普通函数。
  • 你如何以及在哪里打电话给getField
猜你喜欢
  • 2021-10-17
  • 2019-10-18
  • 2019-10-23
  • 2020-07-09
  • 1970-01-01
  • 1970-01-01
  • 2020-01-14
  • 2019-12-29
  • 1970-01-01
相关资源
最近更新 更多