When making small programs, do you often encounter these two synchronization problems:
1. When using a for loop, the operation in one loop has not yet ended, and the next loop has already started. If there is no interdependence between loops, the problem should not be big, but if the start of the next loop depends on the result of the previous loop, then there will be problems with this series of operations, such as drawing:
for (let index in images) { //每画一张图,都要在上一张图画结束才能开始,因为要计算画图位置 ctx.drawImage }
2 . Call the server interface to access data, download pictures, etc., but the server has not returned the data and the code has continued to execute other codes. This will obviously cause problems.
wx.downloadFile({ url: URL, success(wr) { //如果其他执行代码在success代码块里面,还能保证在成功获取数据后正常执行 //如果下载功能是共用的,其他操作逻辑肯定就会抽离出来,这样就保证不了同步执行了。 } });
How to solve it?
In the first case, many solutions on the Internet are to add sync or await, and some add setInterval. I did not choose any of these solutions, and used nested calls.
/** * 处理图片 */ handleOneImage: function(ctx, images, idx) { let that = this; let oneImage = images[idx]; let pro = new Promise(function(resolve, reject) { if (oneImage == undefined) { //画图结束 //执行一系列操作 } else { //成功画图结束,执行下一张图的操作 that.drawOneImage(ctx, oneImage, that.data.xp).then(isSuccess => { if (isSuccess == 'success') { that.handleOneImage(ctx, images, idx + 1); } }); } }); return pro; }, /** * 画图片 */ drawOneImage: function(ctx, image, xp) { let that = this; //保证获取图片信息、画图等操作同步进行结束再返回结果 let pro = new Promise(function(resolve, reject) { wx.getImageInfo({ src: image, success: function(imageInfo) { let iWidth = imageInfo.width; let iHeight = imageInfo.height; let dWidth = (iWidth * 580) / iHeight; ctx.drawImage(image, xp, 0, dWidth, 580); ctx.stroke(); that.setData({ xp: that.data.xp + dWidth }); resolve('success'); } }); }); return pro; },
Second case: In fact, the code to solve the first case is also used to solve the second case. Using Promise, you can study the above code if necessary.
These solutions are also code snippets from a small program of mine. Xiaocheng’s name is Tu Zuo Yao. It is a small and beautiful small program for image synthesis and cutting. Everyone is welcome to try it.
Recommended tutorial: "WeChat Mini Program"
The above is the detailed content of Solve the problem of code synchronization execution in small programs. For more information, please follow other related articles on the PHP Chinese website!