起因:同事发现一个外层数组为0,但长度为2,这种“奇怪”的数据结构
正确的数据结构
原因:循环中执行异步请求导致的
复现业务代码:
//模拟ajax请求
function ajax(){ let data = [{name:'小明',age:22},{name:'小红',age:18}] return new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve(data) },200) }) } //因业务要求,循环中调用接口 function run(){ let userList = [{id:1},{id:2}]; let list = []; userList.forEach((item)=>{ ajax().then((res)=>{ list.push(res) }) }) console.log(list) } run()
解决方式一 :Promise.all
function ajax() { let data = [{ name: '小明', age: 22 }, { name: '小红', age: 18 }] return new Promise((resolve, reject) => { setTimeout(() => { resolve(data) }, 200) }) } 创建Promise方法 function createPromise() { let promise = new Promise((resolve, reject) => {
//将业务接口的返回值,resolve进去 ajax().then((res) => { resolve(res) }) }) return promise } function run() { let userList = [{ id: 1 }, { id: 2 }]; let list = []; let resList = []; userList.forEach((item) => { list.push(createPromise()) }) Promise.all(list).then((res) => { resList = res }) } run()
缺点:
1.Promise.all得等所有请求成功,才能返回,会遇到阻塞问题
2.Promise.all得等所有请求响应,响应时间太长问题
解决方式二 :递归调用接口
function ajax() { let data = [{ name: '小明', age: 22 }, { name: '小红', age: 18 }] return new Promise((resolve, reject) => { setTimeout(() => { resolve(data) }, 200) }) }
递归终止条件,数组长度小于 async function run(length, arr) { const res = await ajax(); arr.push(res) if (length> 1) { await run(length- 1, arr) } return arr } async function getResult() { let userList = [{ id: 1 }, { id: 2 }]; let res = await run(userList.length, []); } getResult()