|
1137 | 1137 | * </div>
|
1138 | 1138 | */
|
1139 | 1139 |
|
| 1140 | + |
| 1141 | +/** |
| 1142 | + * Asynchronous Asset Loading with Async/Await. |
| 1143 | + * |
| 1144 | + * Using async/await in your p5.js sketch allows you to load assets, such as images and JSON data, |
| 1145 | + * in a straightforward, linear fashion without resorting to nested callbacks. Declaring a function |
| 1146 | + * with the async keyword tells JavaScript that this function will perform asynchronous operations and |
| 1147 | + * will always return a promise. Within an async function, the await keyword pauses the execution until |
| 1148 | + * the promise is resolved, making the code appear synchronous and easier to read and maintain. |
| 1149 | + * |
| 1150 | + * In the example below, setup() is declared as an async function. The await keyword is used to wait for |
| 1151 | + * the loadImage() and loadJSON() functions to complete their asset loading. Once the assets are loaded, |
| 1152 | + * createCanvas() sets up the drawing surface and the assets become available for use. |
| 1153 | + * |
| 1154 | + * ```js |
| 1155 | + * let img, data; |
| 1156 | + * |
| 1157 | + * async function setup(){ |
| 1158 | + * // Wait until the image and JSON data have fully loaded. |
| 1159 | + * img = await loadImage("./my-image.png"); |
| 1160 | + * data = await loadJSON("./my-data.json"); |
| 1161 | + * |
| 1162 | + * // Create the canvas after loading assets. |
| 1163 | + * createCanvas(400, 400); |
| 1164 | + * } |
| 1165 | + * ``` |
| 1166 | + * |
| 1167 | + * @property async/await |
| 1168 | + * @example |
| 1169 | + * <div> |
| 1170 | + * <code> |
| 1171 | + * let img, data; |
| 1172 | + * |
| 1173 | + * async function setup(){ |
| 1174 | + * // Pause execution until the image is loaded. |
| 1175 | + * img = await loadImage("./assets/image.png"); |
| 1176 | + * |
| 1177 | + * // Pause execution until the JSON data is loaded. |
| 1178 | + * data = await loadJSON("./assets/data.json"); |
| 1179 | + * |
| 1180 | + * // Create the canvas where the sketch is drawn. |
| 1181 | + * createCanvas(400, 400); |
| 1182 | + * |
| 1183 | + * // Display the loaded image. |
| 1184 | + * background(220); |
| 1185 | + * image(img, 0, 0); |
| 1186 | + * |
| 1187 | + * // Log the loaded JSON data to the console. |
| 1188 | + * console.log(data); |
| 1189 | + * } |
| 1190 | + * </code> |
| 1191 | + * </div> |
| 1192 | + */ |
| 1193 | + |
1140 | 1194 | /**
|
1141 | 1195 | * A list that keeps several pieces of data in order.
|
1142 | 1196 | *
|
|
0 commit comments