如何在 React js 中进行同步 API 调用请求

How to make synchronous API call request in react js

我是 React js 的初学者,我正在开发一个经常发出 api 请求的小型应用程序。所以我面临的问题是有一个页面,其中包含从数据库预填充的表单字段,如果用户对这些字段进行了更改,我正在 post 将新的字段值发送到数据库。单击提交按钮时调用 saveAndConttinue(),从那里根据条件调用 addNewAddress()。但问题是我从 addNewAddress 得到的响应必须用于队列中的下一个 api 调用,但它需要时间来获得响应,并且 address_id 具有空值post打电话。有没有什么方法可以让同步调用在不使用 flux/redux 的情况下做出反应?

saveAndContinue(e) {
e.preventDefault();

if(this.props.params.delivery === 'home_delivery' && this.state.counter) {
  this.addNewAddress();
}

console.log('add id is '+this.state.address_id);
const config = { headers: { 'Content-Type': 'multipart/form-data' } };
let fd = new FormData();
fd.append('token', this.props.params.token);
fd.append('dish_id', this.props.params.dish_id);
fd.append('address_type', this.props.params.delivery);
fd.append('address_id', this.state.address_id);
fd.append('ordered_units', this.props.params.quantity);
fd.append('total_cost', this.props.params.total_cost);
fd.append('total_service_charge', this.props.params.service_charge);
fd.append('net_amount', this.props.params.net_cost);
fd.append('hub_id', this.props.params.hub_id);
fd.append('delivery_charge', this.props.params.delivery_charge);
fd.append('payment_type', this.state.payment_type);
fd.append('device_type', 'web');

axios.post(myConfig.apiUrl + '/api/foody/orders/purchase' , fd, config)
        .then(function(response){
    if(response.data.success) {
      console.log(response);
      browserHistory.push('/order_confirmed/');
    } else {
      console.log(response);
      //alert(response.data.message)
    }
        });
}

addNewAddress() {
 const config = { headers: { 'Content-Type': 'multipart/form-data' } };
 let fd = new FormData();

  if(this.props.params.user_type === 'new') {
    fd.append('type', 'PRIMARY');
  }

  fd.append('token', this.props.params.token);
  fd.append('block', this.state.block);
  fd.append('door_num', this.state.door_num);
  fd.append('address', this.props.params.address);
  fd.append('locality', this.props.params.locality);
  fd.append('landmark', this.props.params.landmark);
  fd.append('hub_id', this.props.params.hub_id);
  axios.post(myConfig.apiUrl + '/api/user/add-address' , fd, config)
    .then(function(response){
      this.setState({address_id: response.data.data['id']});
      console.log(this.state.address_id);
    }.bind(this));
}

您将不得不在 addNewAddress() 的返回承诺中调用队列中的下一个请求:

addNewAddress() {
  axios.post()...
  .then(function (response) {

    // Set state
    this.setState({address_id: response.data.data['id']});

    // [Call next API request here]
    // ...

  })
}

进行同步调用总是一个坏主意,我个人建议不要这样做,只需在返回的承诺中进行下一次调用,如上所示。