Connecting to the p5.party server and loading a shared object are asynchronous operations, they are tasks that take some time (usually not that long) to complete and you need to explicitly wait for them to finish before moving on to tasks that depend on them. When you call partyConnect() and partyLoadShared() in your preload() function, p5.js will wait for your shared object to be loaded and ready before calling your setup() and draw() functions. This is the easiest way to handle loading and waiting, and you should use this method when you can.

<aside> 🧟

In other words: don't use the callbacks if you can use preload() instead! Preload is just easier.

</aside>

Sometimes you can't connect or load in setup(). Maybe you don't know what room to connect to until you get input from your user. Maybe your sketch needs to create a new shared object while it runs. For both these cases, partyLoadShared() can accept an optional callback parameter. The callback you provide will be called with a reference to the shared object when it is ready to be used.

partyLoadShared("shared", (sharedObject) => {
    console.log("The shared object is ready!", sharedObject);
});

When using callbacks you don't need to call partyLoadShared() from preload(), but keep the following in mind.

Related Examples

callbacks

Common Questions

  1. Can I use a callback function for any of the other p5.party functions?

    Yes, you can. All other functions can easily be run from draw() or using event handlers like keyPressed() or mouseMoved().