图像加载中的异步等待 [英] async await in image loading
本文介绍了图像加载中的异步等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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)
以上是我的代码.我有一个图像 url 并尝试使用 async await 获取图像的属性,但它不起作用,不明白我错过了什么.
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.
推荐答案
您的问题来自 await
...
Your problem here extends from the definition for await
...
await
操作符用于等待 Promise
Image.prototype.onload
属性不是承诺,您也不会为其分配.如果您想在加载后返回 height
属性,我会创建一个 Promise
...
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)
})
或者,如果在 async
函数中
or, if within an async
function
async function logImageHeight(imageUrl) {
console.log('height', await tmp.addImageProcess(imageUrl))
}
这篇关于图像加载中的异步等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文