0
<body>
  

  
<div id='heroImage'><img src='' alt=''></div>
<button id='newHero'>Get New Hero</button> 


  <script src="script.js"></script>

 
</body>


const img=''
let getSuperHero=(id)=>{
const newHeroDiv=document.getElementById('newHero')
const heroImageDiv=document.getElementById('heroImage')
let img;

 fetch(`https://superheroapi.com/api.php/5930076870393724/${id}`)
.then(response => response.json())              
.then(json => {
    img=json.image.url
  console.log(img)
    })
}


getSuperHero(300)

document.querySelector('body').innerHTML += `<img src= '${img}' height=300 width=300>`





This outputs a broken images.I know it works if I write the last line inside getSuperHero() function.But as 'img' is declared outside of the function shouldnt it work here as well.

  • This exact type of question is asked dozens a times of day on Stackoverflow [How to return values from async functions using async-await from function?](https://stackoverflow.com/questions/49938266/how-to-return-values-from-async-functions-using-async-await-from-function) – Andy Ray Feb 25 '23 at 06:24
  • Example of this exact question asked recently https://stackoverflow.com/questions/75563556/how-to-make-javascript-wait-for-all-images-to-load-before-proceeding – Andy Ray Feb 25 '23 at 06:26

0 Answers0