Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript executing multiple functions in sequence

I have 3 functions StepONE, StepTWO, StepTHREE to run them in sequence. Is this the correct way to run in sequence :

Also, on using StepTWO(StepTHREE()); the sequence goes wrong, so I did this to make it work : StepTWO(function() { StepTHREE() });

<div id="stepslog"></div>
<div id="count"></div>
<button onclick="Steps()">Start </button>
<script>
 function Steps() {
  StepONE(function() {
    <!-- StepTWO(StepTHREE()); -->
    StepTWO(function() {
      StepTHREE()
    });
    alert('FINISHED WITH BOTH STEPS');
  });
}
function StepONE(callback) {
  <!-- alert('Step ONE'); -->
  document.getElementById('stepslog').innerHTML += '<hr>Step ONE';
  for (i = 1; i < 700; i++) {
    var abc = document.getElementById("count");
    abc.innerHTML += '<br>' + i;
  }
  callback(itemexists);
}
function StepTWO(callback, itemexists) {
  <!-- alert('Step TWO'); -->
  document.getElementById('stepslog').innerHTML += '<hr>Step TWO';
  callback();
}
function StepTHREE() {
  document.getElementById('stepslog').innerHTML += '<hr>Step THREE';
}
</script>

UPDATE :

How do I return values from function 2 & 3 and use it finally in StepONE() function ? callback(itemexists)....is this correct?

like image 866
sqlchild Avatar asked Sep 18 '25 04:09

sqlchild


1 Answers

Try using Promise.resolve and chain the rest of the functions

function Steps() {
  Promise.resolve(StepONE()).then(function(x) {
    console.log('From 1st function ', x);
    return StepTWO();
  }).then(function(y) {
    console.log('From 2nd function ', y);
    StepTHREE();

  })
}

function StepONE() {
  document.getElementById('stepslog').innerHTML += '<hr>Step ONE';
  for (i = 1; i < 700; i++) {
    var abc = document.getElementById("count");
    abc.innerHTML += '<br>' + i;
  }
  return 'Return from ONE';
}

function StepTWO() {
  document.getElementById('stepslog').innerHTML += '<hr>Step TWO';
  return 'Return from TWO';
}

function StepTHREE() {
  document.getElementById('stepslog').innerHTML += '<hr>Step THREE';
}
<div id="stepslog"></div>
<div id="count"></div>
<button onclick="Steps()">Start </button>
like image 189
brk Avatar answered Sep 19 '25 19:09

brk