企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
>[success] # 利用图片预加载学会一些异步骚操作 ~~~ 1.利用 'reduce' 进行有序的异步加载请求 2.利用 for...of 进行有序请求 3.利用 Promise.all 做控制请求并发 ~~~ >[danger] ##### 利用reduce 来做 ~~~ const loadImage = urlId =>{ const url =`https://xxxx/${urlId}` return new Promise((resolve,reject) =>{ const img = new Image(); img.onerror = function(){ console.log("失败"); reject(urlId) } img.onload = function(){ console.log("成功"); resolve(urlId) } img.src = url }) } const urlIds = [1,2,3,4] urlIds.reduce((acc,id)=>{ return acc.then(()=>loadImage(id)) },Promise.resolve()) ~~~ >[danger] ##### for of 配合awiter ~~~ const loadImage = urlId =>{ const url =`https://xxxx/${urlId}` return new Promise((resolve,reject) =>{ const img = new Image(); img.onerror = function(){ console.log("失败"); reject(urlId) } img.onload = function(){ console.log("成功"); resolve(urlId) } img.src = url }) } const idls = async ()=>{ const ls = [1,23,4,5,6] for(let i of ls){ await loadImage(i) } } ~~~ >[danger] ##### 利用map 将promise 整体包裹 ~~~ // 利用map 配合promise all const loadImage = urlId =>{ const url =`https://xxxx/${urlId}` return new Promise((resolve,reject) =>{ const img = new Image(); img.onerror = function(){ console.log("失败"); reject(urlId) } img.onload = function(){ console.log("成功"); resolve(urlId) } img.src = url }) } const ids = [1,2,3,4,5] const promiseArray = ids.map(id=>loadImage(id)) Promise.all(promiseArray).then(()=>{}) ~~~