Sunny
Sunny

Reputation: 187

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

Upvotes: 10

Views: 23699

Answers (3)

bitsapien
bitsapien

Reputation: 1833

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.

Upvotes: 8

Batajus
Batajus

Reputation: 6257

To get a valid response you should adjust your code a bit, because currently you're returning the string "result" and not the array from your promise.

In your getFieldsApi method you can do following:

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

And you would call it like:

const result = await this.getFieldsApi();

Upvotes: 3

imjared
imjared

Reputation: 20554

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.

Upvotes: 9

Related Questions