前言
最近,项目需要新加一个用户发布文章的功能,因为小程序选取的图片都是临时路径,所以需要上传到服务器转为网络图片路径再发布出去。但是小程序上传图片只支持单张图片,在这种情况下图片的上传完成后输出的顺序、判断图片是否全部上传完成等,都是一些需要注意的点。在 Promise 的中有一个 Promise.all 的方法(简单来说就是当所有的异步请求成功后才会执行),在这个方法的帮助下,这些问题都迎刃而解。
代码
export const uploadImage = (tempFilePaths)=>{
return new Promise((presolve,preject)=>{
if({}.toString.call(tempFilePaths)!='[object Array]'){
throw new TypeError(`上传图片参数 tempFilePaths 类型错误!`)
}
//路径数组为空时 不上传
if(tempFilePaths.length==0){
presolve([])
return
}
wx.showLoading({
title: '上传图片中...',
mask:true
});
getToken().then(token => {
let uploads = []
tempFilePaths.forEach((item,i)=>{
uploads[i] = new Promise ((resolve)=>{
wx.uploadFile({
url:'http://www.baidu.com/post',
filePath: item,
name: 'file',
heade
1853




被折叠的 条评论
为什么被折叠?



