Estoy tratando de implementar una clasificación rápida en javascript y necesito await sleep() dentro de una función, pero cuando estoy usando async , la función no obtiene el resultado correcto.
Al eliminar async del código de función de partition funciona bien.
¿Alguien puede ayudar?
async function partition(low, high) { var pivot = random_numbers[low]; // random_number is a global variable contains 10 random number var i = low+1; var j = high; while (i <= j){ if (random_numbers[i] < pivot){ i++; }else{ swap_values(i, j); // this will swap values in random_numbers swap_boxes_sq(i, j); // this will perform some animation await sleep(MAX_SLEEP_TIME); // MAX_SLEEP_TIME = 2000 and sleep is defined in other file j--; } } swap_values(low, i-1); return i-1; } function sort_q( low, high) { if (low < high){ var pi = partition( low, high); sort_q(low, pi-1); sort_q(pi+1, high); } } function quick_sort(low, high) { low = 0; high = number_of_box -1; // number_of_box = 10 sort_q(low, high); console.log(random_numbers); }Hizo la partition asíncrona, por lo que debe agregar await en sort_q (y hacerlo asíncrono) y agregar await en quick_sort
El problema es que la partition es asíncrona, por lo que devuelve una Promesa. sort_q no obtendrá el resultado correcto para pi si no espera el resultado de esta Promesa.
async function partition(low, high) { var pivot = random_numbers[low]; // random_number is a global variable contains 10 random number var i = low+1; var j = high; while (i <= j){ if (random_numbers[i] < pivot){ i++; }else{ swap_values(i, j); // this will swap values in random_numbers swap_boxes_sq(i, j); // this will perform some animation await sleep(MAX_SLEEP_TIME); // MAX_SLEEP_TIME = 2000 and sleep is defined in other file j--; } } swap_values(low, i-1); return i-1; } async function sort_q( low, high) { if (low < high){ var pi = await partition( low, high); sort_q(low, pi-1); sort_q(pi+1, high); } } async function quick_sort(low, high) { low = 0; high = number_of_box -1; // number_of_box = 10 await sort_q(low, high); console.log(random_numbers); }