简体   繁体   中英

Am I missing something here regarding async/await?

I'm trying to understand how async/await works, but I know I'm missing something here. This is my current code, which is not creating the state variable testing.

Updated

try {
  const getUpdate = await axios.post(
    `http://domain/rating-engine/v1/rates/${carrier}?plan=${benefitQuery}`,
    obj,
    config,
  );
  this.setState({ testing: getUpdate });
} catch (err) {
  this.setState({ testing: err });
}

I've now re-written the above code and works as expected now. Thanks for the info!

await only runs in async function

componentDidMount = async () => {
  const getUpdate = await axios.post(
    `http://domain/rating-engine/v1/rates/${carrier}?plan=${benefitQuery}`,
    obj,
    config,
  );
  this.setState({ testing: getUpdate });
};

Please try this:

async function getAxiosPost(){
    try {
      const getUpdate = await axios.post(
        `http://domain/rating-engine/v1/rates/${carrier}?plan=${benefitQuery}`,
         obj,
         config,
      );
      this.setState({ testing: getUpdate });
    } catch (err) {}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM