I have an array list of image urls. I want to get an image width and height, to do so, I use:
const url = 'https://via.placeholder.com/350x150'
const img = new Image()
img.addEventListener('load', function () {
const isWide = img.width > img.height
const isTall = img.height > img.width
console.log(url, isWide, isTall, img.width, img.height) // <--- WORKS FINE
img.src = url
})
I have a list of images where I want to extract them all in some one Promise.all(arrayOfImageUrls).
How would I make it Promise so it awaits for all of the urls in the image array to complete ?
Here is my code which does not work, it just ignores the "await" and trigger the function before it was even finished:
const array = [
"https://via.placeholder.com/350x150",
"https://via.placeholder.com/650x250",
"https://via.placeholder.com/350x150",
"https://via.placeholder.com/650x250",
"https://via.placeholder.com/150x550",
"https://via.placeholder.com/510x450",
"https://via.placeholder.com/800x800"
]
function doSomethingAsync(url) {
return new Promise((resolve) => {
const img = new Image()
img.addEventListener('load', function() {
const isWide = img.width > img.height
const isTall = img.height > img.width
img.src = url
resolve({ url, isWide, isTall })
})
})
}
async function doAsync() {
const promises = []
array.forEach(url => {
promises.push(doSomethingAsync(url))
})
console.log('before promise all')
const results = await Promise.all(promises)
console.log('after promise all', results)
}
doAsync()
You have to put img.src = url before waiting for the images to load, not inside the onload handler. You are currently waiting for images with no src to load.
const array = [
"https://via.placeholder.com/350x150",
"https://via.placeholder.com/650x250",
"https://via.placeholder.com/150x550",
"https://via.placeholder.com/510x450",
"https://via.placeholder.com/800x800"
]
function doSomethingAsync(url) {
return new Promise((resolve) => {
const img = new Image();
img.src = url; // <--- Move this line here
img.addEventListener('load', function() {
const isWide = img.width > img.height
const isTall = img.height > img.width
resolve({ url, isWide, isTall })
})
})
}
async function doAsync() {
const promises = []
array.forEach(url => {
promises.push(doSomethingAsync(url))
})
console.log('before promise all')
const results = await Promise.all(promises)
console.log('after promise all', results)
}
doAsync()