如何使用 async/await 将此回调转换为承诺? [英] How to turn this callback into a promise using async/await?
问题描述
以下函数从 url 中获取图像,加载它,并返回其宽度和高度:
function getImageData (url) {const img = 新图片()img.addEventListener('load', function () {返回 { 宽度:this.naturalWidth,高度:this.naturalHeight }})img.src = 网址}
问题是,如果我这样做:
ready () {console.log(getImageData(this.url))}
我得到 undefined
因为函数运行但图像尚未加载.
如何使用await/async只在图片加载完成且宽高已经可用时返回值?
如何使用
async
/await
把这个回调函数变成promise?
你没有.像往常一样,您使用 new Promise
构造函数.没有语法糖.
function loadImage(url) {返回新的承诺((解决,拒绝)=> {const img = new Image();img.addEventListener('load', () => resolve(img));img.addEventListener('错误', 拒绝);//不要忘记这个img.src = url;});}
<块引用>
如何使用 await
/async
仅在照片加载完毕且宽度和高度已经可用时记录值?
你可以做到
异步函数 getImageData(url) {const img = 等待 loadImage(url);返回 { 宽度:img.naturalWidth,高度:img.naturalHeight };}异步函数就绪(){console.log(await getImageData(this.url))}
The following function takes and image from an url, loads it, and returns its width and height:
function getImageData (url) {
const img = new Image()
img.addEventListener('load', function () {
return { width: this.naturalWidth, height: this.naturalHeight }
})
img.src = url
}
The problem is, if I do something like this:
ready () {
console.log(getImageData(this.url))
}
I get undefined
because the function runs but the imaged hasn't loaded yet.
How to use await/async to return the value only when the photo has loaded and the width and height is already available?
How to use
async
/await
to turn this callback function into a promise?
You don't. As usual, you use the new Promise
constructor. There's no syntactic sugar for that.
function loadImage(url) {
return new Promise((resolve, reject) => {
const img = new Image();
img.addEventListener('load', () => resolve(img));
img.addEventListener('error', reject); // don't forget this one
img.src = url;
});
}
How to use
await
/async
to log the value only when the photo has loaded and the width and height is already available?
You can do
async function getImageData(url) {
const img = await loadImage(url);
return { width: img.naturalWidth, height: img.naturalHeight };
}
async function ready() {
console.log(await getImageData(this.url))
}
这篇关于如何使用 async/await 将此回调转换为承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!