I am new to reactJS and am trying to build a sorting visualizer. The problem I am facing is while implementing the quickSort() routine.
My quickSort() routine is as follows:
async quickSort(array, p, r) {
if(p<r){
this.Partition(array,p,r).then((q)=>{
console.log(p, ' ', r)
this.quickSort(array, p, q-1)
this.quickSort(array,q+1,r)
})
}
}
The reason I have a .then with the Partition function is because I am using async/await in the Partition routine for animations. Then the Partition routine returns the value of the partition 'q' and then the recursion can occur. The Partition function returns a promise whose value is the partition value 'q' without which the recursion cannot proceed hence the '.then' part.
Now, the code is running correctly but I want to add a little bit more functionality. I am calling this quickSort() routine from inside of a quickSortHelper() routine. In quickSortHelper() I first disable a button, then call quickSort() and after completion of quickSort() I want to again enable the button.
But the problem is that the quickSort(array, 0 , n-1) returns after only the first call to it and so the button is instantly disabled and enabled without waiting for the entire recursion to unfold.
I tried returning a promise from inside quickSort() to ensure that when the promise is resolved only then do we proceed to enable the button. But the promise resolves after 1-2 iterations (which makes sense because the moment p>r I think the function would return) and so the button gets enabled without waiting for the entire recursion to finish.
Any suggestions on how to fix this? Is there a way to pause execution until the quickSort() completes and then continue on with the work of enabling the button?
async quickSortHelper(){
this.setState({generateButton: true})
console.log(this.state.generateButton)
var array = this.state.array
this.quickSort(array, 0, array.length-1 ).then(()=>{
this.setState({array})
this.setState({generateButton: false})
})
}
Also one more thing, the console.log(this.state.generateButton) outputs false. So it is never setting the state to true? I don't understand why this is happening?