首页 > 解决方案 > 异步函数返回 [object Promise] 而不是实际值

问题描述

我对 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;
  }

标签: javascriptreactjs

解决方案


你不是在等待的价值,result所以你只是得到一个未兑现的承诺。如果你改变

const result = this.getFieldsAPI();

const result = await this.getFieldsAPI();

你会得到你所追求的。您还需要进行getFields()异步操作。


推荐阅读