|
| 1 | +// PromiseAllExample.js |
| 2 | + |
| 3 | +// Declare variables to hold the images we'll load |
| 4 | +let img1, img2, img3; |
| 5 | + |
| 6 | +async function setup() { |
| 7 | + // Add screen reader-friendly text description |
| 8 | + textOutput(); |
| 9 | + |
| 10 | + // Create a canvas where the images will be drawn |
| 11 | + createCanvas(600, 400); |
| 12 | + |
| 13 | + // Set background color to gray |
| 14 | + background(220); |
| 15 | + |
| 16 | + // Configure text appearance |
| 17 | + textAlign(CENTER, CENTER); |
| 18 | + textSize(18); |
| 19 | + |
| 20 | + // Use async/await with Promise.all to load all three images at once |
| 21 | + // This waits untill ALL images are loaded before continuing |
| 22 | + [img1, img2, img3] = await Promise.all([ |
| 23 | + loadImageAsync('https://picsum.photos/100/100?random=1'), // Replace the image links with user wanted images. |
| 24 | + loadImageAsync('https://picsum.photos/100/100?random=2'), |
| 25 | + loadImageAsync('https://picsum.photos/100/100?random=3') |
| 26 | + ]); |
| 27 | + |
| 28 | + // Once all images are ready, draw them on the canvas |
| 29 | + image(img1, 100, 150); // Draw first image at x=100 |
| 30 | + image(img2, 250, 150); // Second image at x=250 |
| 31 | + image(img3, 400, 150); // Third image at x=400 |
| 32 | + |
| 33 | + // Display a message showing that everything is loaded |
| 34 | + fill(0); // Set text color to black |
| 35 | + text("All images loaded!", width / 2, 50); |
| 36 | +} |
| 37 | + |
| 38 | +// Helper function to load images using a Promise |
| 39 | +// Makes loadImage compatible with async/await style |
| 40 | +function loadImageAsync(url) { |
| 41 | + return new Promise((resolve, reject) => { |
| 42 | + // Try to load the image from the given URL. |
| 43 | + //If successful, resolve the promise with the image. If it fails, reject with the error. |
| 44 | + loadImage(url, img => resolve(img), err => reject(err)); |
| 45 | + }); |
| 46 | +} |
0 commit comments