0
https://stackoverflow.com/questions/14651348/checking-if-image-does-exists-using-javascript

Here I found how to check if image exist, though these returns Promise in which there is Boolean stating if image exists or no, I want to save this Boolean to variable so I can use it later, but not sure how to do it, tried many stuffs, but nothing works.

code in question
    function imageExists(url) {
      return new Promise(resolve => {
        var img = new Image()
        img.addEventListener('load', () => resolve(true))
        img.addEventListener('error', () => resolve(false))
        img.src = url
      })
    }
    
    const url = 'http://www.google.com/images/srpr/nav_logo14.png'
    imageExists(url)
      .then(ok => console.log(`RESULT: exists=${ok}`))
      //                    => RESULT: exists=true

I need it to return boolean, rather than console.log, for example

let imgExist = imageExists(url)
      .then(ok => oK )

but this or other attempts dont work, dont really understand this syntax

Jan
  • 247
  • 2
  • 15
  • It's all about scope my friend, but I'm now more wondering about your dev environment rather than how to save. If you put the variable above its function and save it I think it should be available. I'm also concerned on how you handle `Promise` or `Async/Await` as well. – Irfandy Jip Feb 12 '23 at 05:32
  • Maybe provide us with more simplified real-life case, it would help. – Irfandy Jip Feb 12 '23 at 05:33
  • "*I need it to return boolean*" - this is simply not possible. The knowledge whether the image can be loaded successfully will only be available later. You need to wait for it, one way or another. Put all the code that "uses the variable later" in the callback. – Bergi Feb 12 '23 at 05:53

0 Answers0