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;
}
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.
Async functions would always return a Promise
. Promises may be resolved or rejected. You can handle promises in the following ways:
then
:this.getFieldsAPI.then((value) => {
// code on success
}, (errorReason) => {
// code on error
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With