异步函数返回[对象诺言],而不是实际值



我是Reactjs的新手。

我的返回值 async函数

我打电话

const result = this.getFieldsAPI();

结果值是[对象承诺]

我从 console.log("结果:" 结果);

console.log中看到[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;
  }

您不在等待result的值,因此您只能得到一个未实现的承诺。如果您更改

const result = this.getFieldsAPI();

to

const result = await this.getFieldsAPI();

您会得到自己所追求的。您还需要制作 getFields() async。

async函数将始终返回 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,这似乎不那么令人困惑。

要获得有效的响应,您应该稍微调整代码,因为当前您要返回字符串"结果",而不是诺言中的数组。

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

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

,您将其称为:

const result = await this.getFieldsApi();

最新更新