【问题标题】:Promise .then not waiting for response to save承诺。然后不等待响应保存
【发布时间】:2022-11-16 11:51:09
【问题描述】:

我首先发送一个 POST 请求以向表 ORDER 添加一个新职位,然后在该承诺完成后,它向表 ORDER_PRODUCT 发送一个发布请求以将先前的订单与某些产品相关联。问题是,它发生得太快了,尽管使用了 .then,但响应不会在第二次发布之前保存到 const

如果我将这两个帖子请求分开并手动启动它们,那么一切都很好。

const orderHandler = () => {
setError('')

token
  ? axios
      .post(
        'http://localhost:8000/order/',
        {
          notes: notes,
          price: quantPrice,
          city: city,
          street: street,
          zipcode: zipcode,
        },
        {
          headers: {
            Authorization: 'Token ' + token,
          },
        }
      )
      .then((response) => {
        console.log(response.data.id, "wielki chuj")
        setOrderid(response.data.id )
      })
      //.then((response)=>setOrderid(response.data.id ))
      .then(() => console.log(orderid))
      .then(() => {
        cartItems.map((j) =>
          axios.post(
            'http://localhost:8000/orderproduct/',
            {
              order: orderid,
              product: j.id,
              quantity: j.quant,
            },
            {
              headers: {
                Authorization: 'Token ' + token,
              },
            }
          )
        )
      })
      .catch((error) => {
        console.log(error.response.data.body)
        setError(error.response.data.body)
      })
  : setError('You must be logged in')

}

【问题讨论】:

  • 您应该直接从第一个请求的响应中使用订单 ID
  • ^这救了我。谢谢你@subparry 我已经深入尝试强制 setState 返回一个承诺并且没有想到这么简单的事情

标签: reactjs django django-rest-framework


【解决方案1】:

答案是直接将 response.data 传递给第二个 POST,而不是通过状态。这是 subparry 建议的。

.then((response) => {
        cartItems.map((j) =>
          axios.post(
            'http://localhost:........

【讨论】:

    猜你喜欢
    • 2017-06-24
    • 2017-02-03
    • 2019-04-29
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多