javascript - Questions about the execution order of a for loop code
高洛峰
高洛峰 2017-06-24 09:43:08
0
1
754

In the WeChat applet, the function of clicking the canvas to convert it into a picture and then previewing it is implemented. Since the asynchronous method is called in the for loop, according to the online suggestions, an immediate execution function is used inside the for loop. Multiple tests have found that , sometimes the console will first print out "loop index is 1", and then print out "loop index is 0" (for convenience, the model length is 2), leading to a situation like this: you click on the first canvas, As a result, the preview was the second one. I am puzzled and hope God can enlighten me.

<canvas wx:for="{{ model }}" bindtap="previewImg" canvas-id="{{ 'mycanvas' + index }}" data-index="{{ index }}"/>
 // 点击图片进行预览
  previewImg: function (e) {
    var tempFilePathList = [];
    var index = e.target.dataset.index;
    var self = this;
    var loopedModel = self.data.model;
    for (var i = 0; i < loopedModel.length; i++) {
      (function (a) {
        wx.canvasToTempFilePath({
          canvasId: 'mycanvas' + a,
          success: function (res) {
            console.log('loop index is ' + a);
            tempFilePathList.push(res.tempFilePath);
            if (a == loopedModel.length - 1) { // 循环到最后一个了
              console.log('current image is ' + tempFilePathList[index]);
              wx.previewImage({
                current: tempFilePathList[index], // 当前显示图片的http链接
                urls: tempFilePathList // 需要预览的图片http链接列表
              })
            }
          },
          fail: function (res) {
            console.log(res);
          }
        });
      }(i))
    }
  },
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(1)
ringa_lee

This is normal. The time of asynchronous return is uncertain, so if you have two asynchronous methods at the same time, the order of return is also uncertain. I haven't done it with WeChat, but it should also support the h5 synchronization method. You can try it. If it doesn't work, add a variable control. When there are multiple requests in the queue that have not been returned, you will only display the last one, and the others will not be displayed.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template