Tengo una lista de ID y estoy tratando de consultar dos servidores diferentes para cada ID de la lista.
Escribí dos funciones asíncronas task1 y task2 . Estos devuelven un valor del servidor para una identificación dada.
Pude descifrar esta estructura de Promise.all debajo de la cual se puede hacer el mapa. Pero me gustaría que todas estas promesas se completen por completo antes de pasar al siguiente paso. ¿Cómo puedo hacer esto?
Estaba a punto de recurrir a algo como: while page2.task1 == null: wait 5 seconds , pero pensé que primero preguntaría aquí, ¿alguien podría ayudarme a entender la forma correcta de hacer esto?
class Page { task1 = null; task2 = null; input_id_obj = [1, 2, 3, 4, 5, 6] constructor() {} } let page = new Page(); async function task1(id){fetch...} async function task2(id){fetch...} Promise.all( page.input_id_obj.map((val, key)=> async_task1(val.id)) ).then((values) => { page.task1 = values; }); Promise.all( page.input_id_obj.map((val, key)=> async_task2(val.id)) ).then((values) => { page.task2 = values; });Intenté esto pero el archivo console.log todavía imprime NULL.
async function asyncTask1(){ Promise.all( page.input_id_obj.map((val, key)=> async_task1(val.id)) ).then((values) => { page.task1 = values; }); } async function asyncTask2(){ Promise.all( page.input_id_obj.map((val, key)=> async_task2(val.id)) ).then((values) => { page.task2 = values; }); } async function asyncPromAll() { const resultArray = await Promise.all([asyncTask1(), asyncTask2()]); console.log("page.task1=", page.task1); console.log("page.task2=", page.task2); } asyncPromAll()Digamos que tenemos dos funciones asíncronas task1 y task2.
Casi alcanzaste una meta por ti mismo.
async function task1(){...} async function task2(){...}Ahora solo necesitamos crear una matriz de estas tareas y esperar hasta que terminen.
let arr = [task(),task2()]; // results in this case will contain the answers of both of your requests let results = await Promise.all(arr);