arr.forEach(async item => {const res = await fetch(item)console.log(res)})
在forEach/map中使用await会报错 ,或者并没有拿到实际的返回参数。
原因:
https://juejin.cn/post/6844903824453271559#heading-10
https://juejin.cn/post/6999795230430461966
解决方案:
1、使用for…off代替:
for (const item of arr) {const res = await fetch(item)console.log(res)}
2、使用 for循环
for (var i=0;i<arr.length;i++) {const res = await fetch(arr[i])console.log(res)}
合理搭配Promise.all:
getAll() {Promise.all([ this.getAllSourceSql(newNode)]).then(res => {console.log(res)})
},
async getAllSourceSql(data) {const newData = []for (const item of data) {const { resultJson, count } = await API.getSouceSQL(qs.stringify(getSourcceSQLparams))newData.push({count,...item})}return newData},
场景解释:遍历一个数组,将数组的每一项作为入参调用接口,再将返回值拼接push到新数组中,此时,使用Promise.all 等待所有接口返回后 形成一个新数组。
async function allTasks(data) {for (const item of data) {await new Promise((resolve) => {// 异步操作,你的异步操作可能是axios请求 那么就替换为axios操作// this.$axios({// url: "http://localhost:8088'",// method: "post",// data: {},// }).thne((response) => {// //接口返回的参数 自己处理// resolve(response);// });}).then((res) => {//你的操作console.log(res);});}