Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async function returns [object Promise] instead of the real value

I'm very new to ReactJS.

I have some problem with the return value of async function

when I call

const result = this.getFieldsAPI();

the result value is [object Promise]

I see [object Promise] from console.log("result : " + result);

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;
  }
like image 636
Sun Avatar asked Dec 05 '22 10:12

Sun


2 Answers

You're not waiting for the value of result so you just get an unfulfilled promise. If you change

const result = this.getFieldsAPI();

to

const result = await this.getFieldsAPI();

You'll get what you're after. You'll also need to make getFields() async.

like image 189
imjared Avatar answered May 18 '23 00:05

imjared


Async functions would always return a Promise. Promises may be resolved or rejected. You can handle promises in the following ways:

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

You may choose on what fits you best. I personally prefer option 2, which seems less confusing.

like image 44
bitsapien Avatar answered May 18 '23 00:05

bitsapien