Last active
January 16, 2018 07:16
-
-
Save poberwong/9540b78284dac79712393026b06facee to your computer and use it in GitHub Desktop.
use promise instead of callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
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
with this method, you have to use it as a normal function: