如何按顺序 运行 js文件

How to run js files in order

我正在做一些 Web 自动化,当我 运行 chrome 控制台中的代码时,它 运行 如此快速地完成了这些步骤,页面无法在下一个之前进入位置事件。我试图增加延迟,但它并没有减慢速度。现在我注意到,如果我 运行 将代码分解为步骤函数,step1()、step2()、step3() 等。它有效,但当所有步骤都是 运行 直接通过时在同一个 js 文件中,因为我们再次遇到相同的计时问题,代码 运行ning 比网页响应速度更快。我怎样才能 运行 多个 js 文件、Step1() 文件、Step2() 文件、Step3() 文件等来解决这个计时问题?

等待代码

//Wait function
function wait(ms){
    //alert('Waiting');
    ms += new Date().getTime();
    while (new Date() < ms){};
};

当前代码布局

//running section

//Step 1
var fruits = step1();

//Wait 2 Seconds
wait(2000); 

//Step 2
step2(fruits);

//Wait 2 Seconds
wait(2000); 

//Step 3
step3();

//Wait 2 Seconds
wait(2000); 

//Step 4
step4();

目标:

Run: Step1File.js

Run: Step2File.js

Run: Step3File.js

Run: Step4File.js

使用异步等待。将每个函数声明为异步函数,然后将 await 放在代码布局中每个函数调用的前面。

// step 1

async function step1() {
  // do some stuff
}

对所有函数重复

// running section

async function runTheStuff() {

  await step1()
  await step2()
  await step3()

}

runTheStuff()

这已大大简化,但应该可以帮助您入门。 aync/await - 学习它,喜欢它。