How does js ensure that the functions in the array are executed sequentially?

each function renders a different class, after the result, so it needs to be executed in turn, and some parameters need to be passed, similar to the following structure. How to ensure that the number of case2,case executed after case1 execution is uncertain?

  let case1 = function(){
    console.log("case11");
  }
  let case2 = function(){
    console.log("case22"); 
  }
  let case3 = function(){
    console.log("case33");
  }
  const caseList = [
    case1,case2,case3,....
  ];
Mar.28,2021

try changing it to Promise or Generator ..


The rudest way to

is to encapsulate the callback function

promise and generator are a more elegant solution.

however, if there is no asynchronous operation in your function, it must be called sequentially.


you can try async


if there is an asynchronous operation in that function, you can use Promise,. If not, it will be executed sequentially

.
for(let i =0; i <= arr.length; i PP){
    new Promise((resolve, reject) => {
        resolve(arr[i]())
    })
}

or you can try async and await

async function activeClass() {
    for(let i =0; i <= arr.length; i PP){
        await arr[i]()
    }
}

this is probably the way to think about the above. The specific code implementation depends on yourself, and I can help you write a pseudo code

.
Menu