How do I get the return value inside an asynchronous function from the outside?

how do I return the return value of the onload event function through the getColor function?

console.log(getColor(URL));


function getColor (URL) {
  const image = new Image()
  image.onload =  function(){
    return {color: "red"}
  }
  image.src = URL
}

ask for help, thank you!

Sep.16,2021

first, the previous version of promise

function getColor (URL) {
  let image = new Image()
  image.src = URL
return new Promise((resolve,rej)=>{
    image.onload =  function(){
    resolve({color: 'red'})
  }}
)
}
getColor ('https://img.codeshelper.com/upload/img/2021/09/16/kxzekmuzuqv92.jpg')
.then((r)=>{console.log(r)}) //{color: "red"}

onload is asynchronous, so you can only get this value when it is completed asynchronously. It is most convenient to process this value at the correct point in time through the callback function

let callback = (val) => {console.log(val)}
function getColor (URL, cb) {
  const image = new Image()
  image.onload =  function(){
    cb({color: 'red'})
  }
  image.src = URL
}
getColor(URL, callback)
Menu