当前位置:网站首页>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就是一个列表,一个根据你响应顺序执行的列表。
边栏推荐
- leetcode 36. 有效的数独(模拟题)
- 管理方向发展
- Dark Horse 2022 latest redis course notes and knowledge points (for interview)
- VoLTE基础自学系列 | IMS的业务触发机制
- Boot process and service control
- 1. LVGL 8.3 在 Visual Studio 2019 模拟器中的环境搭建
- RDMA
- Kibana:为地图应用选择不同的语言 - Elastic Stack 8.3
- makefile的foreach、filter、filter-out函数
- PoPW代币分配机制或将点燃下一个牛市
猜你喜欢
Static routing principle and configuration
The principle and configuration of VLAN
requests之模拟登录学习
【场景化解决方案】构建医疗通讯录,“慧医钉”助力医院实现数字化管理
静态路由原理与配置
System transformation and subnetting
OpenHarmony Light Smart Product Development Live Notes
Dark Horse 2022 latest redis course notes and knowledge points (for interview)
[Vulnerability reproduction] CVE-2018-7490 (path traversal)
Routing configuration forwarding and experiment
随机推荐
nodeMCU(ESP8266)和RC522的接线图
gin中模型中增删改查+搜索分页
深度学习时代的视频理解综述
Routing configuration forwarding and experiment
GBJ610-ASEMI超薄整流扁桥GBJ610
uniapp编译到小程序后丢失static文件夹问题
Programming a washing machine: garbled characters after string output
Es6连续解构赋值+重命名
ctf misc picture questions knowledge points
Shell programming loop statement and function
Xpath之爬取全国城市名称学习
Where does detection go forward?
BUUCTF MISC刷题笔记(一)
嵌入式之串口中断只能收到一个字节
基于 JSch 实现服务的自定义监控解决方案
leetcode 36. 有效的数独(模拟题)
【场景化解决方案】OA审批与金智CRM数据同步
大端小端存储区别一看即懂
define 可变参数定义
Shell编程之正则表达式