Skip to content

Instantly share code, notes, and snippets.

@poberwong
Last active January 16, 2018 07:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save poberwong/9540b78284dac79712393026b06facee to your computer and use it in GitHub Desktop.
Save poberwong/9540b78284dac79712393026b06facee to your computer and use it in GitHub Desktop.
use promise instead of callback
async function checkImage (file, pixels, onSuccess, onFailed) {
const {width, height} = pixels
return new Promise((resolve, reject) => {
try {
const img = await readImageFromFile(file)
if (img.width !== WIDTH || img.height !== HEIGHT) {
alert(`图标文件必须 ${pixels} 像素`)
} else {
resolve(img)
}
} catch (e) {
reject(e)
}
})
}
usage: checkImage().then(onResolve, onReject)
// you can use it as a normal promise.
@poberwong
Copy link
Author

poberwong commented Nov 23, 2016

with this method, you have to use it as a normal function:

checkImage(file, pixels, result => normal , error => exception)

@poberwong
Copy link
Author

poberwong commented Nov 23, 2016

Firstly, async function returns a promise object. return will be received as params of resolve, throw will be received as params of reject. Thus, you can get the result with await because it is just a promise.
Secondly, of course, you can use it as a normal function. However, you can't get result by calling the function, you have to treat it as a promise. the only way to get some results is callback--an ugly method.

with proper way

async function checkImage (file, pixels) {
  const {width, height} = pixels

  try {
    const img = await readImageFromFile(file)

    if (img.width !== WIDTH || img.height !== HEIGHT) {
      alert(`图标文件必须 ${pixels} 像素`)
    } else {
      return img
    }
  } catch (e) {
    throw e
    alert('读取图片文件失败')
  }
}

you can use it following :

let result = await checkImage(file, pixels)

or

checkImage(file, pixels).then(result => normal, error => exception)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment