我正在编写一个应用程序,在化学反应中在屏幕上绘制粒子。
我已经编写了一个Particle
类,并且想要处理此类中P5.js中加载图片的异步性质。
我的想法是,如果将loadImage()
函数包装在Promise中,则应该能够异步加载所有粒子精灵,然后在P5 Image对象解析后立即执行绘制代码。 / p>
我仅使用loadImage()
的回调功能就可以使此代码正常工作,但最终我不得不将图像对象交给物理库来对粒子运动进行建模,以及其他构造函数,因此Promise模式似乎是正确的解决方案。
class Particle {
constructor(name) {
// Set properties on the Particle
this.imageUrl = "THE_URL";
this.imageObject = null;
}
loadParticleImage() {
console.log("attempting to load image: " + this.imageUrl)
return new Promise(function (resolve, reject) {
loadImage(this.imageUrl, (result) => {
// Sets the image object property to the result for other methods to access
this.imageObject = result;
// Resolves the Promise with the result
resolve(result);
}, reject(Error("Image not found")));
})
}
drawParticle() {
console.log("attempting to draw particle");
this.loadParticleImage().then(function (imageObject) {
// code to draw image and handoff to physics library
}, function (error) {
console.log("imageObject not defined", error);
});
}
}
在主草图文件的setup()
函数中,我将初始化一个粒子并使用类似以下内容的图形进行绘制:
theParticle = new Particle("Water");
theParticle.drawParticle();
我收到一个堆栈错误,说无法加载图像,我也不知道为什么。
attempting to draw particle
particle.js: attempting to load image: img/svg/Water.svg
particle.js: imageObject not defined Error: Image not found
at particle.js
at new Promise (<anonymous>)
at Particle.loadParticleImage (particle.js)
at Particle.drawParticle (particle.js)
at <anonymous>:1:18
答案 0 :(得分:1)
我可以在您的代码中发现两个错误:
您始终会立即致电reject()
。您可能想将回调传递给loadImage
,该回调将拒绝承诺:
loadImage(this.imageUrl, (result) => {
…
}, () => {
// ^^^^^^^
reject(new Error("Image not found"));
});
the this
keyword in your callback is not the one you expect。还要对诺言执行者回调使用箭头函数,以使this
引用您的Particle
被调用的loadParticleImage
实例:
return new Promise((resolve, reject) => {
// ^^
loadImage(this.imageUrl, result => {
this.imageObject = result;
…