javascript - 關于一段 for 循環代碼執行順序的問題
問題描述
在微信小程序里邊實現點擊 canvas 將其轉換為圖片再預覽的功能,由于涉及異步方法在for循環里調用,參考網上建議,在for循環內部使用了一個立即執行函數,多次測試發現,有時候控制臺會先打印出'loop index is 1', 再打印出'loop index is 0',(為方便起見,model長度為2),導致這樣一種情況:你點擊第一張canvas,結果預覽的卻是第二張,百思不得其解,望大神賜教。
<canvas wx:for='{{ model }}' bindtap='previewImg' canvas- 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)) } },
問題解答
回答1:這很正常,異步返回的時間具有不確定性,所以如果你同時有兩個異步方法,返回的先后順序也是不確定的。微信我沒做過,但應該也支持h5的同步方法,你可以試一下,不行的話加個變量控制,當請求隊列里有多個未返回時,你只顯示最后一個,其他的不讓顯示。
相關文章:
1. python - django 里自定義的 login 方法,如何使用 login_required()2. python如何不改動文件的情況下修改文件的 修改日期3. angular.js - Angular路由和express路由的組合使用問題4. angular.js - angularjs 用ng-reapt渲染的dom 怎么獲取上面的屬性5. mysql優化 - mysql count(id)查詢速度如何優化?6. 主從備份 - 跪求mysql 高可用主從方案7. css3 - [CSS] 動畫效果 3D翻轉bug8. angular.js - 不適用其他構建工具,怎么搭建angular1項目9. mysql主從 - 請教下mysql 主動-被動模式的雙主配置 和 主從配置在應用上有什么區別?10. node.js - node_moduls太多了
![css3 - [CSS] 動畫效果 3D翻轉bug](http://www.cgvv.com.cn/attached/image/news/202304/110831f073.png)