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;

```
using async await you can do it

```
let someImage="i-m-a--g-e";
let load = true

function  preload() {
  console.log("running preload",someImage)
   return new Promise((resolve,reject)=>{

        if(load){ return resolve()}else{return reject()}
   }
                     );
}

function setup(){ 
console.log("running setup")
}

(async () => {
    await preload();
    setup();
})();

```

[JavaScript Demo: Promise.reject()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)