该函数旨在遍历数组并将数组中的每个值发布到数据库。如果我使用异步等待功能,我会出错。
错误:不能在异步函数外使用关键字“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] 删除。
我来说两句