async-await的循环请求数据
场景:循环按顺序请求数组中的接⼝,之所以有这样的需要是因为我要请求⼀个接⼝,但是发送的是多个不同的参数,所以我就将参数放到⼀个数组中,想按照数组顺序请求接⼝然后将返回数据放⼊数组中。
当前项⽬中⽤到的是ES6语法async-await,所以就想着将存放接⼝的数组遍历循环请求⼀遍
1. ⾸先想到的⽅法是⽤forEach+async-await循环遍历数组的每⼀项然后请求接⼝,具体代码如下:
let arr =[],result
this.tagKeyList.forEach(async item =>{
result =await leadsService({ tagKey: item })
arr.push(result.data.data.tagKey)
console.log(result.data.data.tagKey)
})
console.log(arr)
leadsService是提前封装好的ajax请求,括号内容为请求参数,通过这种⽅式请求接⼝之后接⼝都正常请求了,但是这⾥的arr数组输出是空,并且是在接⼝内容返回之前就输出了,也就是说这⾥的async-await并没有⽣效,
2.第⼆种⽅案是采⽤for-of+async-await循环遍历数组具体的代码内容如下:
for(let item of this.tagKeyList){
result =await leadsService({ tagKey: item })
arr.push(result.data.data.tagKey)
console.log(result.data.data.tagKey)
await和async使用方法)}
console.log(arr)
这种情况下的输出顺序就是按照接⼝数组请求数据进⾏输出的,最后才会输出数组内容,可以达到我
的需求
3.第三种思路是通过采⽤promise+async-await的⽅法操作,具体的实现代码如下:
const promises = tagKeyList.map(async(item)=>
result =await leadsService({ tagKey: item })
);
await Promise.all(promises);
console.log('Finished!');
这种⽅式可以实现等待所有接⼝请求完成之后再输⼊请求的内容,但是Promise.all ⽅法会按照并⾏的模式,将所有请求⼀次性全部发送出去,然后等待接收到全部结果后,按照顺序打印出来⽽已。它并不会按照顺序发送⼀个请求,收到结果后再发送下⼀个请求。所以也不符合我所预想的结果。所以只有第⼆种for-of循环的⽅式符合我的需求。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。