Temp.js
export default class Temp {
async addImageProcess(src){
let img = new Image();
img.src = src;
return img.onload = await function(){
return this.height;
}
}
}
另一个文件.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)
上面是我的代码。我有一个图像 url 并尝试使用 async await 获取图像的属性,但它不起作用,不明白我错过了什么。
最佳答案
您的问题来自 the definition for await
...
The
await
operator is used to wait for aPromise
Image.prototype.onload
属性不是一个 promise ,您也没有给它赋值。如果您想在加载后返回 height
属性,我会创建一个 Promise
...
addImageProcess(src){
return new Promise((resolve, reject) => {
let img = new Image()
img.onload = () => resolve(img.height)
img.onerror = reject
img.src = src
})
}
然后您将使用以下内容来访问该值
tmp.addImageProcess(imageUrl).then(height => {
console.log(height)
})
或者,如果在 async
函数中
async function logImageHeight(imageUrl) {
console.log('height', await tmp.addImageProcess(imageUrl))
}
关于javascript - 图片加载异步等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46399223/