【问题标题】:JS, use of Async Await function in Axios when mapping over an arrayJS,映射数组时在Axios中使用Async Await函数
【发布时间】:2020-11-07 13:10:09
【问题描述】:

该函数旨在循环遍历数组并将数组中的每个值 POST 到数据库。如果我使用 async await 函数会出错。

错误:不能在异步函数之外使用关键字“等待”

 const myfunction = async () => {
    [1,2,3].map((item) => {
      
      const endpoint = "/api/";

      await apiService(endpoint, "POST", item)
        .then((r) => console.log(r))
        
    });
  };

apiservice 函数使用浏览器获取函数和存储的 cookie

这可能与以下问题Using async await when mapping over an arrays values重复,但我不明白。

【问题讨论】:

  • 您的 apiService 调用在地图回调中,这意味着您需要将该函数更改为异步:.map(async(item) ....)
  • 只是循环遍历数组的意图吗? .map() 可能有点矫枉过正。可以使用简单的for 循环或for (item of array) {..}
  • @ambianBeing 我会按照建议使用谢谢。

标签: javascript reactjs


【解决方案1】:

原因是await 不会直接出现在您的async 函数中,而是出现在传递给.map(不是async)的函数中。

另外,.map 在这里被滥用了,因为你没有在回调中返回任何东西,也没有使用.map 返回的数组。

只需使用 for 循环即可:

const myfunction = async () => {
    for (let item of [1,2,3]) {      
        const endpoint = "/api/";
        await apiService(endpoint, "POST", item)
            .then((r) => console.log(r))
    }
}

另外,在这里使用then 是一种反模式,因为await 实际上是为了避免使用它。所以最好像这样编码:

const myfunction = async () => {
    for (let item of [1,2,3]) {      
        const endpoint = "/api/";
        let r = await apiService(endpoint, "POST", item)
        console.log(r);
    }
}

【讨论】:

  • 感谢您的澄清。
  • 按照您的建议,我将把异步密钥工作放在上述函数中的什么位置?
  • async 可以保持原样。为清楚起见,我添加了您在我的答案中也有的函数包装器。
【解决方案2】:
const myfunction =  () => {
    [1,2,3].map( async(item) => { // async should be here
      
      const endpoint = "/api/";

      await apiService(endpoint, "POST", item)
        .then((r) => console.log(r))
        
    });
  };

【讨论】:

    【解决方案3】:

    这应该可以工作

     const myfunction = () => {
        [1,2,3].map(async (item) => {
          
          const endpoint = "/api/";
    
          await apiService(endpoint, "POST", item)
            .then((r) => console.log(r))
            
        });
      };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      • 1970-01-01
      • 2021-08-15
      • 2023-03-04
      • 2020-08-13
      • 2022-10-04
      • 2021-05-22
      相关资源
      最近更新 更多