简体   繁体   中英

Stop executing other functions after using await?

I have some issues using recursive with "async" and "await". In the code below I created a function "wait" returning a promise which I call in another function "Partition" to add some delay in a loop. After, I call this function inside "QuickSort" to implement some recursion. The first call of the "partition" function inside performed as expected. After this the value is passed inside of the callback "then" to start performing the function "quicksort", but after performing the first "await" inside this recursion the code pass to the second recursion of the second "quickSort" function inside the callback "then" without finishing the first previous recursion.

I guess this behavior is expected because I'm using the "async" "asynchronous" in the partition function, so this allows the other code to be executed.

 * delay in some functions. This works wll
 * in loops with the use of 'async' and 'await'
 * @param {int} ms - The time to delay;
 */
function wait(ms) {
  return new Promise(r => setTimeout(r, ms));
}
/**
 * This function perform the partition in an
 * array to perform the Quick Sort
 * @param {int} array - The numbers to be sorted
 * @param {int} low - The low index of the array
 * @param {int} high - The high index of the array
 */
async function partition(array, low, high) {
  /* This pivot is place at the rigth position */
  var pivot = array[high];
  var index = low - 1;
  /* Get all the columns child nodes */
  var columnNodes = document.getElementById("flex-box").childNodes;
  var parentElement = document.getElementById("flex-box");
  /* Change the color of the Pivot */
  var pivotColumnNode = columnNodes[high];
  pivotColumnNode.style.backgroundColor = "pink";

  for (let i = low; i < high; i++) {

    // /* Reset the color of the previous Index nodes */
    // if (columnNodes[i - 1] !== undefined) {
    //   columnNodes[i - 1].style.backgroundColor = "blueviolet";
    // }
    /* Change color of value being compare to Pivot node */
    var iNode = columnNodes[i];
    // iNode.style.backgroundColor = "red";
    if (array[i] < pivot) {
      index += 1;
      //Replace the values
      var valueofIndexElement = array[index];
      array[index] = array[i];
      array[i] = valueofIndexElement;

      /* Chnage the color of the node index to be chnanged */
      var nodeIndexElement = columnNodes[index];
      iNode.style.backgroundColor = "yellow";
      nodeIndexElement.style.backgroundColor = "brown";

      var nodeIndexElementClone = nodeIndexElement.cloneNode(true);
      var nodeIElementClone = iNode.cloneNode(true);

      parentElement.replaceChild(nodeIElementClone, columnNodes[index]);
      parentElement.replaceChild(nodeIndexElementClone, columnNodes[i]);
      //await wait(1000);
      nodeIElementClone.style.backgroundColor = "blueviolet";
      nodeIndexElementClone.style.backgroundColor = "blueviolet";
    }
    console.log("New Array: ", array);
    console.log("*********************************");
  }
  var valueOfLastGreaterElement = array[index + 1];
  array[index + 1] = pivot;
  array[high] = valueOfLastGreaterElement;

  /* Chnage the last node elements */
  var pivotColumnNodeClone = pivotColumnNode.cloneNode(true);
  var greaterColumnNodeClone = columnNodes[index + 1].cloneNode(true);

  parentElement.replaceChild(pivotColumnNodeClone, columnNodes[index + 1]);
  parentElement.replaceChild(greaterColumnNodeClone, columnNodes[high]);
  /* Reset the color of the Pivot node */
  pivotColumnNodeClone.style.backgroundColor = "blueviolet";
  greaterColumnNodeClone.style.backgroundColor = "blueviolet";

  console.log("Last: ", array);
  return index + 1;
}
/**
 * This sorts the array with the help of the partition
 * function. This uses recursion to divide an conquer the
 * array.
 * @param {int} array - The numbers to be sorted.
 * @param {*} low - The first index of the array '0'
 * @param {*} high - The length of the array.
 */
function quickSort(array, low, high) {
  debugger;
  if (low < high) {
    debugger;
    partition(array, low, high).then(value => {
      debugger;
      alert(value);
      quickSort(array, low, value - 1); // Before the partition index
      quickSort(array, value + 1, high); // After the partition index
    });
    debugger;
    // partition(array, low, high).then(value => {
    //   debugger;
    //   alert(value);
    //   quickSort(array, value + 1, high); // After the partition index
    // });
  }
}

The thing that I want to accomplish is how to use await in the partition function, and use this function in a recursive way on the "QuickSort" function.

Yes, your quicksort function does some asynchronous things as well now that it is calling an async partition function. But in the code

quickSort(array, low, value - 1); // Before the partition index
quickSort(array, value + 1, high); // After the partition index

the second calls doesn't wait for the first one to finish, so they will run the two partitionings concurrently. You need to chain them - using either explicit promise chaining

function quickSort(array, low, high) {
  if (low < high) {
    return partition(array, low, high).then(value => {
      alert(value);
      return quickSort(array, low, value - 1).then(() => { // Before the partition index
        return quickSort(array, value + 1, high); // After the partition index
      });
    });
  } else {
    return Promise.resolve();
  }
}

or using async / await syntax:

async function quickSort(array, low, high) {
  if (low < high) {
    const value = await partition(array, low, high)
    alert(value);
    await quickSort(array, low, value - 1); // Before the partition index
    await quickSort(array, value + 1, high); // After the partition index
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM