xxxxxxxxxx
102
const DELAY = 5000;
const myAsyncMethod = () => {
return new Promise((resolve) => {
setTimeout(() => resolve("hello world"), DELAY);
});
};
const myCallbackMethod = (onDone) => {
setTimeout(() => {
onDone("hello world");
}, DELAY);
};
class AsyncLoadedObject {
constructor(onDone) {
this.data = "";
this.isReady = false;
myAsyncMethod().then((data) => {
this.data = data;
this.isReady = true;
onDone?.(this);
});
}
}
const asyncLoadedObject = (onDone) => {
return new AsyncLoadedObject(onDone);
};
class CallbackLoadedObject {
constructor(onDone) {
this.data = "";
this.isReady = false;
myCallbackMethod((data) => {
this.data = data;
this.isReady = true;
onDone?.(this);
});
}
}
const callbackLoadedObject = (onDone) => {
return new CallbackLoadedObject(onDone);
};
const myLib = {
asyncLoadedObject,
callbackLoadedObject,
myAsyncMethod,
myCallbackMethod,
};
const myLibOriginal = { myLib };
p5.prototype.myLibInit = function () {
console.log("init", "this", this);
const increment = this._incrementPreload.bind(this);
const decrement = this._decrementPreload.bind(this);
myLib.callbackLoadedObject = function (args) {
increment();
// TODO: handle multiple arguments
const wrappedOnDone = (result) => {
args[0]?.(result);
decrement();
};
return myLibOriginal.callbackLoadedObject(wrappedOnDone);
};
};
p5.prototype.registerMethod("init", p5.prototype.myLibInit);
let sketch = function (p) {
// console.log("p", p, p._incrementPreload, p._decrementPreload, p.registerPreloadMethod, p.prototype);
var x = 100;
var y = 100;
var xy;
var text = "";
var obj = {};
p.preload = function () {
// obj = p.callbackLoadedObject();
obj = myLib.callbackLoadedObject();
};
p.setup = () => {
p.createCanvas(400, 400);
xy = new p5.Vector(100, 100);
};
p.draw = () => {
p.background(0);
p.fill(255);
if (!obj.isReady) {
console.log("did not wait");
}
p.text(obj.data, x, y);
};
};
let myp5 = new p5(sketch);