问题
Temp.js
export default class Temp {
async addImageProcess(src){
let img = new Image();
img.src = src;
return img.onload = await function(){
return this.height;
}
}
}
anotherfile.js
import Temp from '../../classes/Temp'
let tmp = new Temp()
imageUrl ="https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png"
let image = tmp.addImageProcess(imageUrl);
console.log(image)
Above is my code. I have a image url and tried to get image's properties using async await but it's not working, don't understand what I missed.
回答1:
Your problem here extends from the definition for await...
The
await
operator is used to wait for aPromise
The Image.prototype.onload
property is not a promise, nor are you assigning it one. If you're wanting to return the height
property after loading, I would instead create a Promise
...
addImageProcess(src){
return new Promise((resolve, reject) => {
let img = new Image()
img.onload = () => resolve(img.height)
img.onerror = reject
img.src = src
})
}
You would then use the following to access that value
tmp.addImageProcess(imageUrl).then(height => {
console.log(height)
})
or, if within an async
function
async function logImageHeight(imageUrl) {
console.log('height', await tmp.addImageProcess(imageUrl))
}
回答2:
While the proposed solution works perfect, I want to be able to avoid writing promises for every asynchronous function, so I wrote a generic utility function just for this purpose:
in javascript
function onload2promise(obj){
return new Promise((resolve, reject) => {
obj.onload = () => resolve(obj);
obj.onerror = reject;
});
}
in typescript (including some generic typechecks):
interface OnLoadAble {
onload: any;
}
function onload2promise<T extends OnLoadAble>(obj: T): Promise<T> {
return new Promise((resolve, reject) => {
obj.onload = () => resolve(obj);
obj.onerror = reject;
});
}
In the example of the question, you can now do:
async function addImageProcess(src){
let img = new Image();
let imgpromise = onload2promise(img); // see comment of T S why you should do it this way.
img.src = src;
await imgpromise;
return this.height;
}
Off course, the call in anotherfile.js should still happen asynchronously as well, as explained in the last codeblock of Phils answer
来源:https://stackoverflow.com/questions/46399223/async-await-in-image-loading