There are many ways of small program asynchronous data processing, I use async asynchronous function to solve, before also used recursive way to deal with asynchronous data, but the recursive way has limitations.

1. The applets themselves do not support async asynchronous functions, so they need to introduce external dependencies. GitHub download package: github.com/zarknight/o…

I have copied the regenerator folder from the lib folder directly into my utils folder and referenced it in the require folder. Note that the variable name must be regeneratorRuntime.

2. Use of asynchronous functions

 let app = getApp();
 const regeneratorRuntime = require('.. /.. /.. /utils/regenerator/runtime-module'); //async Asynchronous functions depend on the package asyncfunction uploadImgs() {// Upload the imagefor (leti = 0; i < arr.length; I++) {try {// grab reject() errorlet resulte = await uploadImg(arr[i]);
     }catch (err) {
       console.log('err', err); }}}functionUploadImg (file) {// Upload a single imagereturn new Promise((resolve, reject) => {
     wx.uploadFile({
       url: app.globalData.newUrl + '/API/File/Upload/' + app.globalData.token,
       filePath: file,
       name: 'test',
       success(res) {
         if (res.statusCode == 200) {
           resolve(res.data);
         } else{ reject(res.data); // Throw error console.log("err", res.data);
         }
       },
       fail(err) {
         reject(err);
         console.log("err", err);
       }
     })
   })
 }

   uploadImgs(arr);
Copy the code

If you do not understand async asynchronous functions, you can first see the great God (Ruan Yifeng) tutorial: es6.ruanyifeng.com/#docs/async

Two, recursive processing of asynchronous data

    let app = getApp();
    let arr = ['/images/1.png'.'/images/2.png'.'/images/3.png'.'/images/4.png'];
    let index = 0;
    functionUploadImgs (arr, index = 0) {wx.uploadFile({url: app.globaldata.newurl +'/API/File/Upload/' + app.globalData.token ,
        filePath: arr[index],
        name: 'test',
        success (res) {
          if (res.statusCode == 200) {
            index++;
            if(arr.length == index) {// The image has been uploadedreturn; } uploadImgs(arr, index); // Upload the next image}else {
            console.log("err", res.data);
          }
        },
        fail (err) {
          console.log("err", err);
        }
      })
    }

    uploadImgs(arr, index);
Copy the code

The main thing here is to wait for the result of the asynchronous callback success before calling the method itself, and then process the next data from the ARR. Until index == arr.length stops recursing.

This approach has major limitations. If you have to do data processing after a successful upload and then upload the next file, the code here is complicated and not very readable.

The above is the use of asynchronous functions in small programs and advantages, if any friends have better methods and insights, welcome to comment.