我目前有两个文件。
delay.js :出于演示目的以简化示例,假设该文件包含单个异步函数。 (显然实际文件要复杂得多)
var delay = (ms) => (new Promise(res => setTimeout(res, ms))); delay(4000) .then( () => console.log('delay.js has finished');
gravity.js:一个简单的 Canvas Playground :
// Canvas settings:
const canvas = document.querySelector('canvas');
const c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// in case somebody re-sizes the window
canvas.addEventListener("resize", function(){
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
function CanvasEl(x, y, v, width, height, f, g){
this.x = x;
this.y = y;
this.v = v;
this.draw = function(){
c.fillRect(this.x, this.y, width, height);
}
this.gravitate = function(){
if ( this.y + height >= window.innerHeight){
this.v = -this.v;
this.v = this.v * f;
} else {
this.v += g;
}
this.y += this.v;
this.draw();
}
}
var rect = new CanvasEl(0, 0, 2, window.innerWidth, 50, 0.76, 0.56);
function animate(){
window.requestAnimationFrame(animate); // recursive (loop) for animation
c.clearRect(0, 0, canvas.width, canvas.height);
rect.gravitate();
}
animate();
<canvas></canvas>
Now what I want to achieve:
Is to somehow link these two files together, basically oncedelay.js
finishes, only thengravity.js
should fire.
有没有办法以某种方式应用 .then( () => animate())
,而不必将 gravity.js
代码复制粘贴到 delay.js
? -- 基本上我更喜欢将两个文件分开
我知道 Promise.all
和 await
命令,但我想不出一种方法,如何在没有代码的情况下应用它们文件。
最佳答案
您需要将指示 delay.js
结果的 promise 存储在全局变量中:
// delay.js
…
var gravityResult = delay(4000)
.then( () => console.log('delay.js has finished');
然后您可以在其他文件中使用它:
// gravity.js
…
gravityResult.then(animate); // instead of calling `animate()` right away
适本地命名全局变量(或者甚至使用适当的模块系统来避免全局变量并获得声明性依赖),如果可能的话,用动画实际等待的值来解析 promise 。
关于javascript - 如何处理两个单独文件中的异步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54393405/