【问题标题】:I am getting error while calling functions inside mapped array in React JS在 React JS 中调用映射数组内的函数时出现错误
【发布时间】:2022-01-18 00:27:18
【问题描述】:

其实我是通过数组映射来调用函数

let artistId = artist._id;
orderData.products.map((cartproduct, index) => {
const sendOrderData = {
        product: cartproduct._id,
        qty: cartproduct.qty,
      };
  createOrder(userId, sendOrderData).then((data) => {
         if(data.error){
            console.log(data.error)
            }else{
           updateOrderDetails(artistId,sendData).then((response) => {
                if(response.error){
                    console.log(response.error)
                   }else{
                    console.log("done)
                  }
})

但是在对第一个元素完成 updateOrderDetails 函数调用之前,会为下一个元素调用 createorder 函数,因此我无法充分更新数据。

UpdateOrderDetails 进行 API 调用:

export const updateOrderDetailsOfArtist = (artistId, data) => {
  return fetch(`${API}/artist/updateorderdetails/${artistId}`, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  })
    .then((response) => {
      return response.json();
    })
    .catch((err) => console.log(err));
};

【问题讨论】:

  • 也许使用await ?
  • 我怎么用,你能给我发个例子吗
  • await updateOrderDetails(artistId)...
  • 我应该把异步放在哪里?

标签: javascript arrays reactjs express


【解决方案1】:

所以,无论您在哪里编写了 updateOrderDetails(artistId) 函数, 添加async

async function updateOrderDetails(artistId) {
...
// where ever you're using the return statement type await
return await response
}

但为了获得更好的答案,您需要显示 updateOrderDetails 函数的作用、返回的内容、调用的 API 正在做什么。

【讨论】:

  • 这没有成功
  • 您能向我们展示更多您的代码吗?
  • 实际上我通过有条件地请求 updateorderdeatils 解决了这个问题
猜你喜欢
  • 2021-10-12
  • 2020-05-15
  • 1970-01-01
  • 2018-11-19
  • 2020-09-25
  • 2021-07-17
  • 2012-10-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多