Estoy tratando de entender cómo usar await en mi situación.
tengo este código:
updateMap() { this.paramsTemp = 0; if(this.updateMapCheck == true){ this.loading = true; this.arrOfDisplays.forEach((display, index) => { if (display.removed == true) { if (this.locationsToSend[index + 1]) { this.drawOneTrip(index, index + 1, index); // here after first one finish we go to another call, here i need await? display.removed = false; } } }); // after finish above i want to go to this.markerArr... this.markersArr.forEach((marker, index) => { marker.set("label", { text: "" + index, color: "white" }); }); // here most important, if above finish i want to call this.changeTime() // wait to finish every think above to call changeTime() this.changeTime(); // while every think finish in changeTime() i want to do last 2 line. this.loading = false; this.map.setZoom(14); } else{ this.showToasterErrorUpdateMap(); } }toda la información necesaria la puse en código.
¿Cómo usar await en la situación anterior?
antes estoy usando setTimeout para cada paso con tiempo aproximado, pero no funciona perfectamente porque probablemente el compilador vaya a otro paso antes de terminar el primer paso.
Array.prototype.map y Promise.all . map creará una matriz de Promises y luego se resolverá usando await Promise.all([]) await Promise.all(arrOfDisplays.map(async (elem, index) => { if (display.removed == true) { if (this.locationsToSend[index + 1]) { await this.drawOneTrip(index, index + 1, index); display.removed = false; } } }) );Más sobre el mapa: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Y sobre Promise.All: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
Puede usar 'aguardar' dentro de cualquier función que haya declarado como 'asincrónica' y usar 'aguardar' para esperar a que finalice cualquier llamada de función asíncrona antes de pasar a la siguiente línea de código, por lo que realmente depende de cuál de sus llamadas de función son asincrónico.
Suponiendo que drawOneTrip, marker.set y changeTime sean asíncronos, entonces:
async updateMap() { this.paramsTemp = 0; if(this.updateMapCheck == true){ this.loading = true; this.arrOfDisplays.forEach((display, index) => { if (display.removed == true) { if (this.locationsToSend[index + 1]) { await this.drawOneTrip(index, index + 1, index); // here after first one finish we go to another call, here i need await? display.removed = false; } } }); this.markersArr.forEach((marker, index) => { await marker.set("label", { text: "" + index, color: "white" }); }); await this.changeTime(); this.loading = false; this.map.setZoom(14); } else{ this.showToasterErrorUpdateMap(); } }Por supuesto, si alguna de estas funciones no es asíncrona, no tiene sentido poner await delante de su llamada.