Question: How do I write a function where everything within the function gets loaded before another function is called? For example, (similar to P5.js) I want to implement a preload function that will load anything that needs to be loaded (ie Images) before executing a setup function.

```
let someImage;
function preload() {
   someImage = new Image();
   someImage.src = "some URL";
   someImage.onload = imageLoaded;
}
function imageLoaded() {
   //this is called before setup
}
function setup() {
   //I can safely assume everything is properly loaded
}

```

Answer: 
To preload an image, you need to actually be careful what order you supply the values. If you add `src` before `onload` it is possible that the image will load before the `onload` function will run.

It is annoyingly more possible than it sounds. Same thing goes for `<script>` as well.

Here's how I would do it:

```js
let someImage;
function preload() {
  someImage = new Image();
  return new Promise((resolve, reject) => {
    // this will pass the event object in the .then function
    someImage.onload = resolve;

    // Optional if you want to handle images not loading
    // someImage.onerror = reject;

    someImage.src = "some URL";
  });
}

// Now you can do it two ways depending on what floats your boat
// You can change your setup function to be async/await
async function setup() {
  try {
    let imageResult = await preload();
    imageLoaded();
    // code that would be in your original setup function
  } catch (e) {
    // handle error
  }
}

// Or you can do promise chaining with callbacks
preload()
  .then(loadEvent => imageLoaded())
  .then(() => setup());
  // .catch(error => handleError(error)); // Optional;

```
The best way to implement that in Javascript is to have your preload function return a promise, then put all of your code in the promise success return. If you want functions called in a certain order, then you can do a promise chain.

```
let someImage;
function preload() {
   someImage = new Image();
   someImage.src = "some URL";
   someImage.onload = imageLoaded;
   return new Promise((resolve)=>resolve());
}
preload().then(function(){
    setup();
});
function setup() {
}

```

<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise>

<https://javascript.info/promise-chaining>