当前位置:网站首页>js在for循环中按照顺序响应请求
js在for循环中按照顺序响应请求
2022-08-09 08:54:00 【Your-Nikee】
在某些坑爹的小程序中,原型链并没有formData,只能使用他的uploadfile方式对图片进行上传,而且单次只能上传一张图片,要是我们想让这个上传的动作同步执行怎么办呢。
我们选中图片的时候会得到一个图片的列表比如
filePath:[
'https://assasass/123123.png',
'https://assasass/123124.png',
'https://assasass/123125.png'
]
三张图片。
上传的时候,你可能需要
for(let i in filePath){
uni.uploadFile({
//...
success:res=>{
//得到响应数据
},
fail:err=>{
//响应失败内容
}
})
}
但是这个时候,我们并不知道每次请求需要花费的时间,有可能在文件大小不一的情况下,第一次请求还没得到响应,第二次请求就已经响应成功了。
为了避免这个问题,我们可以:
const temp = [];
for(let i in filePath){
temp.push(
new Promise((resolve,reject)=>{
uni.uploadFile({
//...
success:res=>{
//得到响应数据
resolve(res)
},
fail:err=>{
//响应失败内容
reject(err)
}
})
})
)
}
将所有的请求先组装为一个promise装到列表中,再利用promise的all方式去执行他们。
Promise.all(temp).then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
这时候的res就是一个列表,一个根据你响应顺序执行的列表。
边栏推荐
- ctfshow-web入门 文件上传篇部分题解
- 智慧图书馆的导航方案-定位导航导览-只用一个方案全部实现
- leetcode 36. 有效的数独(模拟题)
- Go语言技巧之正确高效使用slice(听课笔记总结--简单易懂)
- GBJ610-ASEMI超薄整流扁桥GBJ610
- jdbctemplate connects to sql server, the data found in the code is inconsistent with the database, how to solve it?
- The principle and configuration of VLAN
- PoPW代币分配机制或将点燃下一个牛市
- BUUCTF MISC brush notes (2)
- Three handshakes, four waves
猜你喜欢
1. LVGL 8.3 在 Visual Studio 2019 模拟器中的环境搭建
【场景化解决方案】OA审批与金智CRM数据同步
正则之re模块
Redis缓存设计
Account and Permission Management
requests之防盗链学习
零搜索量的关键词,你需要布局吗?
Regular Expressions for Shell Programming
智慧图书馆的导航方案-定位导航导览-只用一个方案全部实现
【MySQL】mysql:解决[Err] 1093 - You can‘t specify target table ‘表名‘ for update in FROM clause问题
随机推荐
VoLTE基础自学系列 | IMS的业务触发机制
PoPW token distribution mechanism may ignite the next bull market
fastadmin图片上传方法改造
医院智能3D蓝牙导航导诊系统
静态路由原理与配置
Programming a washing machine: garbled characters after string output
探索APP性能优化之稳定性优化(解决方案)
UE4 RTS 框选功能实现
leetcode 35. 搜索插入位置(二分法+找性质也很关键)
智慧图书馆的导航方案-定位导航导览-只用一个方案全部实现
JVM进程诊断利器——Arthas
XCTF高校战“疫”网络安全分享赛Misc wp
【场景化解决方案】构建门店通讯录,“门店通”实现零售门店标准化运营
QT设置exe可执行文件的图标
Notes on OpenHarmony Open Source Meeting (Nanjing Station)
Operator Overloading in Inheritance: A Legend of Input and Output
Literature retrieval operation code
三次握手,四次挥手
requests之防盗链学习
Process synchronization and mutual exclusion problem