skip to Main Content

How to call a function after the previous function is complete? In the code below the second_function() is executed before the first_function() and the data get suffled

first_function();
second_function();

function name() {
  if (condition == true) {
    let tdbody = document.createElement('td');
    tdbody.classList.add("class1");
    let tdbodytext = document.createTextNode(userincourseres[i].fullname);
    tdbody.appendChild(tdbodytext);
    trbody.appendChild(tdbody);
  }
}


async function first_function() {
  await name();
  if (condition == true) {
    var tdbody = document.createElement('td');
    var tdbodytext = document.createTextNode(get_grade_res.grade);
    tdbody.classList.add("class2");
    tdbody.appendChild(tdbodytext);
    trbody.appendChild(tdbody);
  }
}

function second_function() {
  if (condition == true) {
    var tdbody = document.createElement('td');
    var tdbodytext = document.createTextNode(get_grade_res.grade);
    tdbody.classList.add("class3");
    tdbody.appendChild(tdbodytext);
    trbody.appendChild(tdbody);
  }

2

Answers


  1. The behaviour is expected, please have a look of the below example.

    first_function();
    second_function();
    
    function name() {
      console.log("name");
    }
    
    async function first_function() {
      await name();
      console.log("first");
    }
    
    function second_function() {
      console.log("second");
    }

    It can be written as

    function name() {
      console.log("name");
    }
    
    function second_function() {
      console.log("second");
    }
    
    Promise.resolve(name()).then(() => {
      console.log("first");
    });
    
    second_function();
    Login or Signup to reply.
  2. Either do it like this

    first_function().then(() => first_function())
    

    Or if you want to use the asyncawait syntax

    async function callingFunc() {
       await first_function();
       second_function();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search