Es probable que este código no funcione porque la conexión con mongo no se establece lo suficientemente rápido. Así que pensé que tenía que cambiarlo a una función asnyc. Pero definitivamente no sabe por dónde empezar. Soy nuevo en Node y Mongo
| izquierda |
|---|
| Julián Graber 900 1 |
| demostración de windows 673 3 |
| portátilDemo 640 4 |
| IpadDemo 628 5 |
Debería verse así, pero mongo lo actualiza para que cada rango tenga el mismo dígito.
// function for giving rank function giveRank(arrayArg,resultArg){ // declaring and initilising variables let rank = 1; prev_rank = rank; position = 0; // displaying the headers in the console console.log('\n-------OUR RESULTS------\n'); console.log('Name | Mark | Position\n'); // looping through the rank array for (i = 0; i < arrayArg.length ; i ++) { /* If it is the first index, then automatically the position becomes 1. */ if(i == 0) { position = rank; Ranking.find({name: arrayArg[i]}).then((data) => { if(data){ updateRank(bla, bla, bla) }else{ newRank(bla,bla,bla); } }); /* if the value contained in `[i]` is not equal to `[i-1]`, increment the `rank` value and assign it to `position`. The `prev_rank` is assigned the `rank` value. */ } else if(arrayArg[i] != arrayArg[i-1]) { rank ++; position = rank; prev_rank = rank; Ranking.find({name: arrayArg[i]}).then((data) => { if(data){ updateRank(bla, bla, bla) }else{ newRank(bla,bla,bla); } }); /* Otherwise, if the value contained in `[i]` is equal to `[i-1]`, assign the position the value stored in the `prev_rank` variable then increment the value stored in the `rank` variable.*/ } else { position = prev_rank; rank ++; Ranking.find({name: arrayArg[i]}).then((data) => { if(data){ updateRank(bla, bla, bla) }else{ newRank(bla,bla,bla); } }); } } }Para convertir una llamada asíncrona basada en una cadena de promesas en una llamada asíncrona/en espera, solo necesita hacer un par de cosas:
Convierta la función principal en una función asíncrona usando la palabra clave async , así: function myFunction (...) {} se convierte en async function myFunction (...) {}
Use la palabra clave await delante de su llamada de función, así: doStuff(...) se convierte en await doStuff(...)
Convierta el parámetro a su primera devolución de llamada .then() al valor de retorno de la llamada asíncrona, así: doStuff().then((data) => {}) se convierte en let data = await doStuff()
Mueva el cuerpo de la devolución de llamada .then() debajo de la asignación de la respuesta, así: doStuff().then((data) => { console.log(data) }) se convierte en let data = await doStuff(); console.log(data);
Entonces, en su ejemplo, convertir una de las funciones se vería así:
async function giveRank(arrayArg,resultArg){ ... ... if(i == 0) { position = rank; let data = await Ranking.find({name: arrayArg[i]}) if(data){ updateRank(bla, bla, bla) }else{ newRank(bla,bla,bla); } } ... ... }