xxxxxxxxxx
126
const DELAY = 1000;
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 registerAll = (p5Source) => {
const register = p5Source.registerPreloadMethod || p5Source.prototype?.registerPreloadMethod;
const increment = p5Source._incrementPreload;
const decrement = p5Source._decrementPreload;
/*
register("asyncLoadedObject", myLib);
register("callbackLoadedObject", myLib);
register("myAsyncMethod", myLib);
register("myCallbackMethod", myLib);
*/
Object.keys(myLib).forEach((name) => {
const original = myLib[name];
const wrapped = (onDone) => {
increment();
original((res) => {
onDone?.(res);
decrement();
})
}
myLib[name] = wrapped;
})
}
// registerAll(p5);
const myLibOriginal = { myLib }
p5.prototype.callbackLoadedObject = function(args) {
this._incrementPreload();
const decrement = this._decrementPreload;
// TODO: handle multiple arguments
const wrappedOnDone = (result) => {
args[0]?.(result);
this._decrementPreload();
}
return myLibOriginal.callbackLoadedObject(wrappedOnDone);
}
myLib.callbackLoadedObject = p5.prototype.callbackLoadedObject;
let sketch = function (p){
// console.log("p", p, p._incrementPreload, p._decrementPreload, p.registerPreloadMethod, p.prototype);
//registerAll(f);
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);