- 关于一段for循环代码执行顺序的问题
-
聚码交流
-
0
1

- yhuxAvNbtxUM
0000-00-00 00:00:00
- 回帖
在微信小程序里边实现点击canvas将其转换为图片再预览的功能,由于涉及异步方法在for循环里调用,参考网上建议,在for循环内部使用了一个立即执行函数,多次测试发现,有时候控制台会先打印出"loopindexis1",再打印出"loopindexis0",(为方便起见,model长度为2),导致这样一种情况:你点击第一张canvas,结果预览的却是第二张,百思不得其解,望大神赐教。<canvaswx:for="{{model}}"bindtap="previewImg"canvas-id="{{'mycanvas'+index}}"data-index="{{index}}"/>//点击图片进行预览previewImg:function(e){vartempFilePathList=[];varindex=e.target.dataset.index;varself=this;varloopedModel=self.data.model;for(vari=0;i<loopedModel.length;i++){(function(a){wx.canvasToTempFilePath({canvasId:'mycanvas'+a,success:function(res){console.log('loopindexis'+a);tempFilePathList.push(res.tempFilePath);if(a==loopedModel.length-1){//循环到最后一个了console.log('currentimageis'+tempFilePathList[index]);wx.previewImage({current:tempFilePathList[index],//当前显示图片的http链接urls:tempFilePathList//需要预览的图片http链接列表})}},fail:function(res){console.log(res);}});}(i))}},