在React中使用Stripe和Axios链接异步函数调用

时间:2019-01-09 09:34:33

标签: javascript reactjs stripe-payments axios

因此,我尝试提交用户输入其信用卡的订单。

为此,我调用order方法,该方法对Stripe(createSource)进行API调用以创建付款来源。然后,使用axios将订单参数发布到我的Rails后端,在其中我发送刚创建的源的ID(source.id

async order() {
      let {source} = await this.props.stripe.createSource({type: 'card', currency: 'eur', owner: {email: this.props.currentUserEmail}});
      axios.post("/orders", {sourceId: source.id,
                              mealId: this.props.mealId,
                              price: this.state.mealPrice,

                              selectedPickupTime: this.state.selectedPickupTime
                            })
}

问题是,当axios将发布请求发送到后端时,我认为尚未创建源,因为出现以下错误:

Unhandled Rejection (TypeError): Cannot read property 'id' of undefined for source.id

在axios发送发布请求之前,如何更改它并等待创建源?

3 个答案:

答案 0 :(得分:4)

创建源时可能会出现错误。根据条纹docs,您需要以这种方式检查请求是否成功。

async order() {
      // Either Source or Error
      let {source, error} = await this.props.stripe.createSource({type: 'card', currency: 'eur', owner: {email: this.props.currentUserEmail}});

      if (error) { // there was an error
        console.error('Unable to create a source due to', error) 
      } else {
        axios.post("/orders", {sourceId: source.id,
                              mealId: this.props.mealId,
                              price: this.state.mealPrice,

                              selectedPickupTime: this.state.selectedPickupTime
                            })
     }
}

答案 1 :(得分:1)

docs看来,执行此操作的正确方法是:

class CheckoutForm extends React.Component {
  handleSubmit = (ev) => {
    // We don't want to let default form submission happen here, which would refresh the page.
    ev.preventDefault();
    this.props.stripe.createSource({type: 'card', currency: 'eur', owner: {email: this.props.currentUserEmail}})
      .then(source => axios.post("/orders", {sourceId: source.id, mealId: this.props.mealId, price: this.state.mealPrice, selectedPickupTime: this.state.selectedPickupTime }))
      .catch(err => console.log(err));

  }
};

答案 2 :(得分:1)

在您的情况下,异步功能出错。为您的实现使用try-catch来处理承诺拒绝。

async order() {
  try {
    let source = await this.props.stripe.createSource({ type: 'card', currency: 'eur', owner: { email: this.props.currentUserEmail }});
    axios.post("/orders", {
      sourceId: source.id,
      mealId: this.props.mealId,
      price: this.state.mealPrice,
      selectedPickupTime: this.state.selectedPickupTime
    });
  }
  catch (err) { // there was an error
    console.error('Unable to create a source due to', error)
  }
}