React JS 意外的保留字“await”

Shu*_*ade 6 javascript async-await

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

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" } })
}
Run Code Online (Sandbox Code Playgroud)

下面是我调用该函数的函数。

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

小智 8

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

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

应该 :

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


Bla*_*mba 6

代替

const handleSubmit = () => {
     
Run Code Online (Sandbox Code Playgroud)

const handleSubmit = async () => {
     
Run Code Online (Sandbox Code Playgroud)

为了await工作,它需要被包装在异步函数中