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?
2 Answers 2
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>
You're making this way too complicated.
If you want to run three functions in sequence, one after the other, just write the calls in sequence:
stepOne();
stepTwo();
stepThree();
That will call the three functions listed, one after the other. Each function will fully complete its execution before the next function is called.
This is the normal and expected way to run JavaScript functions. You don't need callbacks, or promises, or any of that. Just call the functions.
Regarding your update, if you need to return a value from one function and then pass that value to another function, simply do exactly that:
let valOne = stepOne();
let valTwo = stepTwo( valOne );
stepThree( valTwo );
Now if you're dealing with server requests, or anything else asynchronous, that is a different story. But nothing in your question indicates this. Sequential execution is the normal way that JavaScript works, so just use it unless you need something different.
StepONE(() => StepTWO(() => StepTHREE))