有的接口只能传单个参数,需要多次调用接口可以:
// 使用 Promise.allasync getApi() {const arr = [1,2,3,4]let res = await Promise.all(arr.map(item => {return api({ params: item })}))console.log('res', res)}
另外,map() 是无法中断循环跳出的,有需要中断只能改用for循环。
arr.map(async) 是并发,所有任务都是同步发出去,但是每一个 map 循环里面的 await 会单独暂停。
for(await) 是遇到一个 await 就暂停执行,任务都是异步,做完才会下一个任务。
<template><div class="hello">异步处理</div></template><script>import dayjs from 'dayjs'export default {name: 'awaitStep',data(){return {arr: [0, 1, 2, 3, 4, 5]}},mounted(){this.run()this.run2()},methods:{delay(number){return new Promise((resolve) => {setTimeout(() => {console.log(dayjs(Date.now()).format('YYYY-MM-DD HH:mm:ss'))resolve(number)}, 1000)})},async run() {for (let i = 0; i < this.arr.length; i++) {const num = await this.delay(i)console.log('for', num)// 思考一下 num 打印的时间}},async run2() {this.arr.map(async(i) => {const num = await this.delay(i)console.log('map', num)})}}}</script>
可以看出map在页面一出现就log出了五条数据,而for await 是异步依次打印出五条数据。
