小程序中将异步请求变成同步请求

本文介绍如何在小程序环境中,利用Promise将原本的异步请求转换为同步操作,以解决在特定场景下需要按顺序执行请求的问题。通过示例代码详细解析Promise的运用,帮助开发者更好地理解和实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用Promise

	//图片上传
    uploadimg:function(a){
        var tt = this
        return new Promise((resolve, reject) =>{
            wx.uploadFile({
                filePath: a,
                name: 'file',
                url: httpsRequest.httpsUrl + resHttp.fileImgIsVideo,
                header: {
                    "content-type": "application/x-www-form-urlencoded",
                    "requesttype": "wxapp",
                    "token": tt.data.tokens
                },
                success(res) {
                	//resolve作用提示小程序请求已结束
                    resolve(JSON.parse(res.data))
                },
                fail (err) {
                  reject(err)
                }
            });
        });
    },
    // 提交数据
    //async关键词
    async submit(e) {
        var that = this,file_url = '';
        //res为上方法请求返回的res.data内容
        var res = await that.uploadimg(that.data.ImgsArr[0])
        wx.request({
            url: httpsRequest.httpsUrl + resHttp.feedback,
            data: {},
            method: "post",
            header: {
                'content-type': 'application/x-www-form-urlencoded',
                "requesttype": "wxapp",
                "token": that.data.tokens
            },
            success(res) {
                console.log(res);
                wx.showToast({
                    title: res.data.msg,
                    icon: 'success'
                })
            }
        })
       
    },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值