javascript - How to turn this getImageData into a promise? -
the following function takes , image url, loads it, , returns width , 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 this:
ready () { console.log(getimagedata(this.url)) }
i undefined
because function runs imaged hasn't loaded yet.
how use await/async (or new promise
) return value when photo has loaded , width , height available?
how use
async
/await
turn callback function promise?
you don't. as usual, use new promise
constructor. there's no syntactic sugar 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 1 img.src = url; }); }
how use
await
/async
log value when photo has loaded , width , height 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)) }
Comments
Post a Comment