首页 新闻 赞助 找找看

微信小程序网络请求如何实现同步?

0
悬赏园豆:20 [已解决问题] 解决于 2017-06-06 22:32

微信小程序的请求默认都是异步的,可是总是有不同的情况。比如近日有个需求,需要先上传完照片再发布文字分享。网上找了很久很多人都说使用Promise。于是我试了下,结果发现不对啊,报错了,现贴上代码如下:

//上传图片
  uploadImages:function(){
    return new Promise(function (resolve, reject) {
      var fileList = new Array(); //文件上传返回的列表
      //上传主题图片 一次只能上传一张好恶心
      for (var i = 0; i < this.data.files.length; i++) {
        wx.uploadFile({
          url: 'http://localhost:8080/cgke/topic/uploadImgs',
          filePath: that.data.files[i],
          name: "files",
          async: false,
          success: function (res) {
            console.log("上传主题图片列表:" + res.data);
            fileList[i] = res.data.data[0];
          }
        })
      }
      //设置变量
      Page.this.setData({
        fileList:fileList
      });
    });
  },
  //发布新主题
  publishTopic:function(){
    return new Promise(function (resolve, reject){
      var fileList=Page.this.data.fileList;
      //发布新主题
      wx.request({
        url: 'http://localhost:8080/cgke/topic/addNew',
        data: {
          userid: getApp().globalData.uid,//发布用户ID
          content: e.detail.value.content,
          ispublic: that.data.isPublic,
          img1: fileList.length > 0 ? fileList[0] : "",
          img2: fileList.length > 1 ? fileList[1] : "",
          img3: fileList.length > 2 ? fileList[2] : "",
          img4: fileList.length > 3 ? fileList[3] : "",
          img5: fileList.length > 4 ? fileList[4] : "",
          img6: fileList.length > 5 ? fileList[5] : "",
          img7: fileList.length > 6 ? fileList[6] : "",
          img8: fileList.length > 7 ? fileList[7] : "",
          img9: fileList.length > 8 ? fileList[8] : ""
        },
        success: function (res) {
          wx.showToast({
            title: "发布成功!"
          });
          wx.switchTab({
            url: '../index/index'
          })
        }
      })
    })
  },
  //提交发布
  doSubmit: function (e) {
    var that = this;
    var topicContent = e.detail.value.content;
    if (topicContent.trim() == "" || topicContent == "请输入文字") {
      wx.showToast({
        title: "主题内容不能为空"
      });
      return;
    }
    if (this.data.files.length == 0) {
      wx.showToast({
        title: "请至少上传一张图片"
      });
      return;
    }
    //先上传图片  再发布主题
    uploadImages().then(publishTopic);
  }

当我按钮绑定

doSubmit时,点击按钮报错了,报错说
uploadImages这个方法在doSubmit方法里面使用了一个未定义的方法引用


        
Mr.xiong的主页 Mr.xiong | 初学一级 | 园豆:79
提问于:2017-06-06 22:12
< >
分享
最佳答案
0

加个this试试

this.uploadImages

收获园豆:20
爱编程的大叔 | 高人七级 |园豆:30839 | 2017-06-06 22:13

 果然就是加一个this的工作    哎   还是自己不够专业   感谢这么快的回复 

Mr.xiong | 园豆:79 (初学一级) | 2017-06-06 22:32
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册