javascript - 如何处理两个单独文件中的异步?

标签 javascript asynchronous include static-linking

我目前有两个文件。

  1. delay.js :出于演示目的以简化示例,假设该文件包含单个异步函数。 (显然实际文件要复杂得多)

    var delay = (ms) => (new Promise(res => setTimeout(res, ms)));
    
    delay(4000)
       .then( () => console.log('delay.js has finished');
    
  2. 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 once delay.js finishes, only then gravity.js should fire.

有没有办法以某种方式应用 .then( () => animate()),而不必将 gravity.js 代码复制粘贴到 delay.js-- 基本上我更喜欢将两个文件分开

<小时/>

我知道 Promise.allawait 命令,但我想不出一种方法,如何在没有代码的情况下应用它们文件。

最佳答案

您需要将指示 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/

相关文章:

php - 在 PHP 中包含太多文件会降低性能吗?

C++/G++ 包括来自另一个文件夹的头文件

javascript - 如何迭代对象内的数组?

java - 如何从java异步发送soap消息

python - 在 python 中将我自己的函数作为 asyncio 函数

asp.net - 在 MVC Action 中启动和忘记异步任务

javascript - 我可以在 JS 对象中设置文本样式吗?

javascript - 如何上传 zip 文件并在 Express js 中为其内容提供永久链接

javascript - 对象的变化是一成不变的吗?

java - JSP include,前后导入代码