Converting Callbacks to Promises Using async/await
Callbacks provide a convenient way to handle asynchronous code. However, using promises with async/await can offer advantages in terms of code readability and maintainability. This question addresses the challenge of converting a callback function that loads an image's width and height into a promise-based implementation.
The provided callback function, getImageData, returns the natural width and height of an image when it finishes loading. However, when invoked asynchronously as shown in the example:
ready () { console.log(getImageData(this.url)) }
The value returned is undefined because the callback is executed immediately, while the image takes some time to load. To overcome this, we can use the Promise constructor to create a promise that resolves once the image is loaded. Here's the updated getImageData function as a promise:
function getImageData(url) { return new Promise((resolve, reject) => { const img = new Image(); img.addEventListener('load', () => { resolve({ width: img.naturalWidth, height: img.naturalHeight }); }); img.addEventListener('error', reject); // Handle errors here img.src = url; }); }
With this promise-based function, we can now use async/await to delay the execution of getImageData and obtain the actual width and height of the loaded image:
async function ready() { const imageData = await getImageData(this.url); console.log(imageData); }
This code ensures that the console logging happens only after the image has fully loaded and its width and height are available.
The above is the detailed content of How to Convert Image Loading Callbacks to Promises Using async/await?. For more information, please follow other related articles on the PHP Chinese website!