javascript - 關(guān)于一段 for 循環(huán)代碼執(zhí)行順序的問題
問題描述
在微信小程序里邊實(shí)現(xiàn)點(diǎn)擊 canvas 將其轉(zhuǎn)換為圖片再預(yù)覽的功能,由于涉及異步方法在for循環(huán)里調(diào)用,參考網(wǎng)上建議,在for循環(huán)內(nèi)部使用了一個(gè)立即執(zhí)行函數(shù),多次測試發(fā)現(xiàn),有時(shí)候控制臺會先打印出'loop index is 1', 再打印出'loop index is 0',(為方便起見,model長度為2),導(dǎo)致這樣一種情況:你點(diǎn)擊第一張canvas,結(jié)果預(yù)覽的卻是第二張,百思不得其解,望大神賜教。
<canvas wx:for='{{ model }}' bindtap='previewImg' canvas- data-index='{{ index }}'/>
// 點(diǎn)擊圖片進(jìn)行預(yù)覽 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) { // 循環(huán)到最后一個(gè)了 console.log(’current image is ’ + tempFilePathList[index]); wx.previewImage({current: tempFilePathList[index], // 當(dāng)前顯示圖片的http鏈接urls: tempFilePathList // 需要預(yù)覽的圖片http鏈接列表 }) } }, fail: function (res) { console.log(res); }}); }(i)) } },
問題解答
回答1:這很正常,異步返回的時(shí)間具有不確定性,所以如果你同時(shí)有兩個(gè)異步方法,返回的先后順序也是不確定的。微信我沒做過,但應(yīng)該也支持h5的同步方法,你可以試一下,不行的話加個(gè)變量控制,當(dāng)請求隊(duì)列里有多個(gè)未返回時(shí),你只顯示最后一個(gè),其他的不讓顯示。
相關(guān)文章:
1. docker綁定了nginx端口 外部訪問不到2. docker網(wǎng)絡(luò)端口映射,沒有方便點(diǎn)的操作方法么?3. docker容器呢SSH為什么連不通呢?4. docker - 各位電腦上有多少個(gè)容器啊?容器一多,自己都搞混了,咋辦呢?5. docker不顯示端口映射呢?6. angular.js - angular內(nèi)容過長展開收起效果7. nignx - docker內(nèi)nginx 80端口被占用8. java - 為什么此私有靜態(tài)變量能被訪問呢?9. fragment - android webView 返回后怎么禁止重新渲染?10. php - mysql 模糊搜索問題
