Skip to content

Commit 4194503

Browse files
authored
Added promise instructions for addons
1 parent 99a5826 commit 4194503

File tree

1 file changed

+47
-1
lines changed

1 file changed

+47
-1
lines changed

README.md

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,53 @@ async function setup() {
9393
}
9494
```
9595

96+
## …using registerPreloadMethod in a addon or library
97+
98+
If your addon built with p5.js 1.x uses `registerPReloadMethod` such as in this example from [p5.sound.js](https://github.com/processing/p5.sound.js):
99+
100+
```js
101+
p5.prototype.registerPreloadMethod('loadSound', p5.prototype);
102+
```
103+
104+
Then to make your addon compatible with **both p5.js 1.x and 2.0**, this this line can be removed (the method `loadSound`, in this example, does not need to be registered) and the method can be updated as follows:
105+
106+
```js
107+
function loadSound (path) {
108+
if(self._incrementPreload && self._decrementPreload){
109+
// tTis is the check to determine if preload() is being used, as with
110+
// p5.js 1.x or with the preload compatibility addon. The function
111+
// returns the soundfile.
112+
113+
self._incrementPreload();
114+
115+
let player = new p5.SoundFile(
116+
path,
117+
function () {
118+
// The callback indicates to preload() that the file is done loading
119+
self._decrementPreload();
120+
}
121+
);
122+
return player;
123+
124+
}else{
125+
// Otherwise, async/await is being used, so the function returns a promise,
126+
// which loads the soundfile asynchronously.
127+
128+
return new Promise((resolve) => {
129+
let player = new p5.SoundFile(
130+
path,
131+
function () {
132+
// The callback resolves the promise when the file is done loading
133+
resolve(player);
134+
}
135+
);
136+
});
137+
}
138+
}
139+
```
140+
141+
And that's it! You can check this example of making an addon backwards-compatible and work with p5.js 2.0 here: [the p5.sound.js example](https://github.com/processing/p5.sound.js/commit/608ffa93f241538c4fb353544f6d01275911d212)
142+
96143
## …making shapes
97144

98145
Short guide coming soon! For now, you can [find out more here](https://github.com/processing/p5.js/issues/6766)
@@ -118,4 +165,3 @@ The below functions are also better supported in JavaScript itself:
118165
* `sort()`
119166
* `splice()`
120167
* `subset()`
121-

0 commit comments

Comments
 (0)