在 `new Image().onload` 中返回 `true` 以验证图像是否存在于 URL?

huangapple go评论77阅读模式
英文:

return true in nested function part of new Image() .onload to verify image exist from url?

问题

如何在函数运行在新的 Image() .onload 的函数部分时返回 true以便验证 URL 是否为有效图像

    var valid = false;
    checkImage('https://example.com/image.png')
    console.log(valid) //第一次运行始终为 false

    function checkImage(url) {
    
      var image = new Image();
      image.onload = function () {
        if (this.width > 0) {
    			valid = true;
        }
      }
      image.onerror = function() {
    		valid = false;
      }
      image.src = url;
    }

我还尝试过设置一个全局变量但这并不起作用或者还有其他通过 checkImage(url) 返回 true/false 的方法吗

 https://stackoverflow.com/a/55880263/8719001 获取了这个初始解决方案
英文:

How can I return true when function is run inside function part of new Image() .onload, in order to verify if a url is a valid image?

var valid = false;
checkImage('https://example.com/image.png')
console.log(valid) //always false at first run

function checkImage(url) {

  var image = new Image();
  image.onload = function () {
    if (this.width > 0) {
			valid = true;
    }
  }
  image.onerror = function() {
		valid = false;
  }
  image.src = url;
}

I also tried setting a global variable which doesn't work,Or any other way to return true / false back via checkImage(url) ?

Got this initial solution from https://stackoverflow.com/a/55880263/8719001

答案1

得分: 1

根据你的代码示例,你需要将结果包装在一个Promise对象中,这是一个用于“稍后返回结果”的对象:

function checkImage(url) {
  return new Promise((resolve, reject) => {
    var image = new Image();
    image.onload = function () {
      if (this.width > 0) {
        resolve()
      } else {
        reject()
      }
    }
    image.onerror = reject
    image.src = url;
  })
}

const valid = await checkImage('https://example.com/image.png')

或者,如果你的唯一目标是检查文件是否存在(而不一定是检查它是否作为图像有效),也可以使用fetch的简单方式:

const exists = await fetch(url, {method: 'HEAD'})
  .then(response => response.status === 200)
英文:

Following your code example you'll need to wrap your result in a Promise, which is an object made for "returning a result later":

function checkImage(url) {
  return new Promise((resolve, reject) => {
    var image = new Image();
    image.onload = function () {
      if (this.width > 0) {
        resolve()
      } else {
        reject()
      }
    }
    image.onerror = reject
    image.src = url;
  })
}

const valid = await checkImage('https://example.com/image.png')

Alternatively, a simpler way of doing this would be to use fetch if your only goal is to check for the file's existence (and not necessarily checking whether it works as an image):

const exists = await fetch(url, {method: 'HEAD'})
  .then(response => response.status === 200)

答案2

得分: 1

    (async () => {
      let valid = await checkImage('https://example.com/image.png')
      console.log(valid)
    })();

    async function checkImage(url) {
      return new Promise(resolve=>{
        const image = new Image()
        image.onload = () => resolve(!!image.width)
        image.onerror = () => resolve(false)
        image.src = url
      })
    }
英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

(async () =&gt; {
  let valid = await checkImage(&#39;https://example.com/image.png&#39;)
  console.log(valid)
})();

async function checkImage(url) {
  return new Promise(resolve=&gt;{
    const image = new Image()
    image.onload = () =&gt; resolve(!!image.width)
    image.onerror = () =&gt; resolve(false)
    image.src = url
  })
}

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月18日 08:37:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75490412.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定