鍍金池/ 問答/HTML/ 如何在vue項(xiàng)目中將獲取圖片寬度和高度尺寸的異步函數(shù)換成同步

如何在vue項(xiàng)目中將獲取圖片寬度和高度尺寸的異步函數(shù)換成同步

1.在上傳前通過獲取input空間中的file文件,想獲取這個(gè)圖片的寬度和高度,但是因?yàn)镕ileReader類和Image類都要異步加載,總是不能同步處理,用了promise 和 async,await嘗試了但是掌握的不好,沒有效果,想請(qǐng)問一下如何修改這段代碼,讓我能夠直接調(diào)用這個(gè)方法就能獲取寬度和高度?

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)
}
回答
編輯回答
硬扛

1.promise化

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.調(diào)用

async function getImg() {
  let img = await util()
  console.log('width', img.width)
  console.log('height', img.height)
}
2017年12月21日 23:05