JS,映射数组时使用Axios中的Async Await函数

阿努普·K·乔治

该函数旨在遍历数组并将数组中的每个值发布到数据库。如果我使用异步等待功能,我会出错。

错误:不能在异步函数外使用关键字“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 array values重复,但我不明白。

特里科特

原因是它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))
    }
}

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章