如何用Promise实现上传多张图片——微信小程序开发

我们知道,微信小程序开发中,有一个wx.uploadFile的API可以让开发者很方便地上传文件,同时该API提供了回调函数success或者是fail,可以在上传完成后执行某些代码。但是在开发过程中,我发现该接口不支持一次上传多张图片,而且不能全部在全部图片上传完成后才执行回调函数。这时候可以使用Promise编程。

先了解一些promisehttps://blog.csdn.net/qq_34645412/article/details/81170576

var promise = Promise.all(that.data.imgsPaths.map((imgPath, index) => {

        return new Promise(function(resolve, reject) {

          if (imgPath != "") {

            wx.uploadFile({

              url:,//开发者服务器url

              filePath: imgPath,

              name: 'file',

              header: {

                "Content-Type": "multipart/form-data"

              },

              formData: {},

              success: function(res) {

                resolve(res.data);//这里要加resolve()函数,参数可为空,不加的话promise无法达到预期效果。

                console.log("success");

              },

              fail: function(err) {

                reject();//同样要加reject

                console.log("fail");

              },

            });

          } else {

            resolve(index);

          }

        });

      }));

      promise.then(function onFulfilled(value) {

    //这里编写回调函数的代码,甚至可以再加一个网络请求的函数

        })

        .catch(function onRejected(error) {

          wx.hideLoading();

          console.log('图片上传失败');

        });

总结:Promise编程可以有多个promise函数一个接一个执行,Promise.all()的参数是一堆的promise,promise其实就是把一段代码框起来,这些代码通常涉及http请求,数据库访问等等,是一个异步过程。程序执行的时候不会等这些过程返回结果(原因之一就是延迟太大),而是直接执行下一条语句,如果你想等这些过程完成后必须执行一些代码,那就用promise编程,在promise的.then()回调函数中以函数的形式给出你想要后执行的代码(该函数作为then()的参数)。

原创文章 26 获赞 33 访问量 1926

猜你喜欢

转载自blog.csdn.net/qq_40765537/article/details/97785304