How to change the asynchronous function of getting the width and height of a picture into Synchronize in a vue project

1. Before uploading by getting the file file in input space, want to get the width and height of this picture, but because the FileReader class and Image class have to load asynchronously, always can not Synchronize processing, using promise and async,await tried but not good, no effect, would like to ask how to modify this code, so that I can directly call this method to get the width and height?

function util() {
  let reader = new FileReader()
  reader.onload = function (e) {
    let data = e.target.result
    let img = new Image()
    img.src = data
    img.onload = function () {
      console.log("width", img.width)
      console.log("height", img.height)
    }
  }
  reader.readAsDataURL(file)
}
Mar.16,2021

1. Innovate

function util() {
  return new Promise((resolve, reject) => {
    let reader = new FileReader()
    reader.onload = function (e) {
      let data = e.target.result
      let img = new Image()
      img.src = data
      img.onload = function () {
        resovle({
          width: img.width,
          height: img.height
        })
        console.log('width', img.width)
        console.log('height', img.height)
      }
    }
    reader.readAsDataURL(file)
  })
}

2. Call

async function getImg() {
  let img = await util()
  console.log('width', img.width)
  console.log('height', img.height)
}
Menu