React中的Axios异步等待

时间:2019-05-29 15:03:06

标签: javascript async-await axios

我正在尝试获取并发布请求,以某种方式延迟了状态的更新(应该先是.get,然后是.post)

async componentDidMount() {

    const {destination, weight} = this.state;


    axios.get(`https://myapi`)
        .then(res => {
            const customer = res.data;

            this.setState({ customer,
                destination: customer[0].address[0].city,
            }
        })

   axios.post(`https://myapi`, {destination, weight})
        .then((post)=>{
          const delivery = post.data;
            this.setState({ delivery,
              cost: delivery[0].cost[0].value
             });
        });

        return post;
}

状态已更新,但帖子以某种方式出现错误,应填写目的地。我发现这的解决方案是使用异步等待。我尝试实现它,但是它不起作用。

这是我尝试过的

async componentDidMount() {

        const {destination, weight} = this.state;


        axios.get(`https://myapi`)
            .then(res => {
                const customer = res.data;

                this.setState({ customer,
                    destination: customer[0].address[0].city,
                }
            })

const post = await axios.post(`https://api.cashless.vip/api/cost`, {destination, weight})
            .then((post)=>{
          console.log(this.state.destination);
              const delivery = post.data;
                this.setState({ delivery,
                  cost: delivery[0].cost[0].value
                 });
            });

            return post;
}

我尝试控制台记录目标状态,是的,它确实已更新。我在做异步等待错误吗?谢谢您的帮助!

1 个答案:

答案 0 :(得分:2)

try{
   let res = await axios.get(`https://myapi`);
   if (res) {
     const customer = res.data;
     this.setState({ customer,
        destination: customer[0].address[0].city,
     });
     const postRes = await axios.post(`https://api.cashless.vip/api/cost`);
     if (postRes) {
       const delivery = post.data;
         this.setState({ delivery,
           cost: delivery[0].cost[0].value
         });
     }
   }
}catch (err) {
  console.log(err);
}

如果您想在外面使用帖子,则取决于您。