如何修改以下回调函数以便它返回一个promise?

时间:2017-06-15 09:19:27

标签: javascript promise

此函数尝试加载图像,如果图像未加载,则再次调用该函数:

function loadImage (url = '', callback = () => {}) {
  utils.loadImage(url, () => {
    callback()
  }, () => {
    loadImage(url, callback)
  })
}

我想让它回来我保证所以我写道:

function loadImage (url = '', callback = () => {}) {
  return new Promise((resolve, reject) => {
    utils.loadImage(url, () => {
      // what to do with resolve and reject
      callback()
    }, () => {
      loadImage(url, callback)
    })
  })
}

但我不确定在哪里解决并拒绝...

1 个答案:

答案 0 :(得分:1)

const loadImage = url => new Promise(resolve => {
  utils.loadImage(url, resolve, () => {
    loadImage(url).then(resolve)
  })
})

Edit: Even better version thanks to Bergi's comment:

const loadImage = url => new Promise(resolve => {
  utils.loadImage(url, resolve, () => resolve(loadImage(url)))
})