【问题标题】:How to run js files in order如何按顺序运行js文件
【发布时间】:2020-08-01 04:58:07
【问题描述】:

我正在做一些网络自动化,当我在 chrome 控制台中运行代码时,它会以如此快的速度运行这些步骤,页面无法在下一个事件之前就位。我试图增加延迟,但它并没有减慢速度。现在我注意到,如果我运行分解为步骤函数的代码,step1(),step2(),step3()等。它可以工作,但是当所有步骤都直接在同一个js文件中运行时就不行了,因为我们得到同样的计时问题再次出现,代码运行速度超过了网页的响应速度。如何运行多个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();

目标:

运行:Step1File.js

运行:Step2File.js

运行:Step3File.js

运行:Step4File.js

【问题讨论】:

标签: javascript google-chrome-devtools webautomation


【解决方案1】:

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

// step 1

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

对所有函数重复

// running section

async function runTheStuff() {

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

}

runTheStuff()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2020-03-15
    相关资源
    最近更新 更多