异步函数返回 [object Promise] 而不是实际值。

9

我很新于ReactJS。

我遇到了一些关于异步函数返回值的问题。

当我调用时:

const result = this.getFieldsAPI();

这里的result值是[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;
  }

1
如果您想获得真正的返回值,请使用 const result = await this.getFieldsAPI(); - Sirko
3
所以,你的意思是异步函数返回一个Promise?我认为这没有问题,因为这就是它们的作用。 - Kevin B
但如果我在getField()前面添加async,它将会抛出错误。 - Sun
我认为你的远程调用只是在不应该的地方。这不是每次渲染发生时都想要运行的东西。 - Kevin B
3个回答

9

你没有等待result的值,因此你只得到了一个未实现的Promise。如果你改变

const result = this.getFieldsAPI();

to

const result = await this.getFieldsAPI();

你会得到你想要的。您还需要将getFields()改为异步操作。


如果我将getField()改为async,就会出现错误。 对象不能作为React的子元素(找到:[object Promise])。 如果您想呈现一组子元素,请改用数组。 - Sun

7

异步函数总是会返回一个 Promise。Promise 可以被解决(resolved)或拒绝(rejected)。你可以使用以下方式处理 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,它更适合我的情况。 - Velojet

3
要获得有效的响应,您应该稍微调整一下代码,因为目前您正在返回一个字符串“result”,而不是来自promise的数组。
在您的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() 为普通函数? - Sun
你是如何以及在哪里调用 getField 的? - Batajus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接