0

I'm working on a web-based visualization tool of algorithms using javascript, so it needs some pause during the execution. To pause execution I used const delay = ms => new Promise(res => setTimeout(res, ms)); and called function await delay(500);, which I found on stack overflow, it worked fine with a non-recursive algorithm. And to make recursive algorithm sequential I used return new Promise((resolve,reject) and .then(). but now I can't use await inside of return new Promise, what is the reason, and am I on right track? my code looks like this(quicksort)

const quick = async(low, high) => 
{   
  return new Promise((resolve,reject) =>
  {

    if (low < high)  
    {  
  
      var pivot = color[high]
      var i = low -1 
  
      for(var j = low; j <= high - 1; j++) 
      {
        // I want some delay here
        if(color[j] < pivot)
        {
          i++
          swap(i,j)  
         // delay here
        }
  
      }
      var pi = i+1;  
  
      swap(pi,high)
  
      // and delay here

      quick( low, pi - 1).then(quick( pi + 1, high));
     
    }
    resolve();
  });
}
Ryu
  • 47
  • 5
  • This looks like the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it), and doesn't make use of `async`/`await` at all – Bergi Jul 11 '20 at 20:02

1 Answers1

1

You don't need return new Promise(... because async functions already return promises. You can't use await because the promise handler is not an async function. Try this:

const quick = async (low, high) => {
    if (low < high) {
        var pivot = color[high];
        var i = low - 1;

        for (var j = low; j <= high - 1; j++) {
            await delay(500);

            if (color[j] < pivot) {
                i++;
                swap(i, j);
                // delay here
            }
        }
        var pi = i + 1;

        swap(pi, high);

        await delay(500);

        await quick(low, pi - 1);
        await quick(pi + 1, high);
    }
    // return is implicit
};
D. Pardal
  • 6,173
  • 1
  • 17
  • 37
  • I removed `return new Promise(...` and now the delay is working but now the left part of `pivot` and right part are exciting simultaneously. – Ryu Jul 11 '20 at 19:13
  • Should the first `await delay(500);` not be inside the `if() {....}` clause? ie delay only if the swap is made. May not make a big difference but that's what the question asks for. – Roamer-1888 Jul 12 '20 at 03:16
  • Sure, you can put the delays wherever you want. – D. Pardal Jul 12 '20 at 07:38
  • @D.Pardal it's working. what was the problem with `.then()`? – Ryu Jul 12 '20 at 09:21
  • You used `then(quick(pi + 1, high))` instead of `then(() => { quick(pi + 1, high); });`, so `quick` was called immediately. – D. Pardal Jul 12 '20 at 11:09