Promise usage scenarios

Usage scenario: In a listing, click a picture in a listing to see a larger image. (vue2)

Problem: You need to know the width and height of the image when viewing a large image with vue-preview, but the interface does not return, so you need to use the Image object to get the width and height of the image.

 arr.forEach((val, indexs) => {
    let img = new Image()
    img.addEventListener('load', () => {
       _this.imgInfoArr.push({
          src: val,
          w: img.width,
           h: img.height
        })
         if (arr.length - 1 === indexs) {
            resolve()
         }
      })
       img.src = val
  })    

Using img's load event to get image width and height is actually an asynchronous operation.

View the js code where the big picture effect appears

this.$preview.open(index, this.imgInfoArr)。
When this step is performed, the asynchronous acquisition of the width and height of the picture above this.imgInfoArr must be completed. So you need to use promises. The complete code is as follows:
// 看大图
    watchBigImg(index, arr) {
      var _this = this
      function getImgInfo() {
        var p = new Promise(function(resolve, reject) {
          _this.imgInfoArr = []
          arr.forEach((val, indexs) => {
            let img = new Image()
            img.addEventListener('load', () => {
              _this.imgInfoArr.push({
                src: val,
                w: img.width,
                h: img.height
              })
              if (arr.length - 1 === indexs) {
                resolve()
              }
            })
            img.src = val
          })
        })
        return p
      }
      getImgInfo ()
        .then((data) => {
          this.$preview.open(index, this.imgInfoArr)
        })
    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324621179&siteId=291194637