小程序同步请求

在做文件上传的时候,我需要使用请求返回来的数据,但是小程序是异步请求的,所以就要解决同步问题

第一步

//发起请求,得到用户实体
function uploadImg(file) {
    return new Promise(function (resolve, reject) {
        wx.uploadFile({
            url: 'https://www.api.com/upload',
            filePath: file,
            name: 'file',
            success: (res) => {
                let result = res.data;
                resolve(result);
            },
            fail: () => {
                reject("系统异常,请重试!")
            }
        })
    })
}

function uploadImgs(files) {
    let that = this
    return new Promise(function (resolve, reject) {
        files.forEach(function (value, index, array) {
            that.uploadImg(value).then((res) => {
                files[index] = res
            }).catch((res) => {
                reject(res)
            })
        })
        console.log(files)
        resolve(files)
    })
}


module.exports.uploadImg = uploadImg
module.exports.uploadImgs = uploadImgs

第二步

let com = require("../../utils/common")
pullbulish: async function (e) {
        let that = this
        const tem = [];
        for (const item of that.data.imgList) {
            await com.uploadImg(item).then(res => {
                tem.push(res)
            })
            console.log(tem)
        }
        that.setData({
            imgList: tem
        })
    },
发布了82 篇原创文章 · 获赞 12 · 访问量 3687

猜你喜欢

转载自blog.csdn.net/weixin_44737877/article/details/103977056