【问题标题】:React JS Unexpected reserved word 'await' [closed]React JS 意外的保留字“等待”[关闭]
【发布时间】:2021-11-05 01:53:38
【问题描述】:

我正在努力解决这个异步等待问题我创建了异步函数,为此我正在调用等待,但我收到错误意外的保留字“等待” 下面是异步函数

export const addProductCall = async (product) => {
    let accessToken = window.localStorage.getItem("accessToken");
    await axios.post(SERVER_URI + '/inventoryservice/v1/item',
        product,
        { headers: { "Authorization": "Bearer " + accessToken, "Content-Type": "application/json" } })
}

下面是我调用这个函数的函数。

const handleSubmit = () => {
        const data = {
            'storeId': customerDetails.id, category, categoryToBeAdded, description,
            productCode, productName, sku, price, unit, quantity
        }
        await addProductCall(data);
    }

【问题讨论】:

标签: javascript async-await


【解决方案1】:

您不能在异步函数之外使用 await 关键字:

const handleSubmit = () => {
  const data = {
    'storeId': customerDetails.id, category, categoryToBeAdded, description,
      productCode, productName, sku, price, unit, quantity
  }
  await addProductCall(data);
}

应该是:

const handleSubmit = async () => {
  const data = {
    'storeId': customerDetails.id, category, categoryToBeAdded, description,
      productCode, productName, sku, price, unit, quantity
  }
  await addProductCall(data);
}

【讨论】:

    【解决方案2】:

    替换

    const handleSubmit = () => {
         
    

    const handleSubmit = async () => {
         
    

    要使await 工作,它需要被包装在一个异步函数中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 2021-12-08
      • 2022-06-10
      • 2021-10-03
      • 1970-01-01
      • 2017-10-06
      • 2020-05-29
      相关资源
      最近更新 更多