如何从外部获取异步函数内部的返回值?

如何通过getColor函数返回onload事件函数的返回值呢?

console.log(getColor(URL));


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

求助,谢谢!!

阅读 4.6k
2 个回答

先上一个promise版的

function getColor (URL) {
  let image = new Image()
  image.src = URL
return new Promise((resolve,rej)=>{
    image.onload =  function(){
    resolve({color: 'red'})
  }}
)
}
getColor ('https://file.iviewui.com/admin-dist/img/login-bg.0899ffa6.jpg')
.then((r)=>{console.log(r)}) //{color: "red"}

onload是异步的, 所以你只能在异步完成的时候获得这个值, 最方便是通过的回调函数在正确的时间点处理这个值

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)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题