I have a list of IDs and I am trying to query two different servers for each ID in the list.
I wrote two async functions task1 and task2. These return a value from the server for a given ID.
I was able to figure out this Promise.all structure below which can do the map. But I would like all of these promises to fully-complete before I move on to the next step. How can I do this?
I was about to resort to something like: while page2.task1 == null: wait 5 seconds but I figured I would ask here first, could someone please help me understand the correct way to do this?
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;
});
I tried this but the console.log still prints 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()
Let's say we have two async functions task1 and task2.
You almost reached a goal by yourself.
async function task1(){...}
async function task2(){...}
Now we just need to create an array of this tasks and wait till they all finish
let arr = [task(),task2()];
// results in this case will contain the answers of both of your requests
let results = await Promise.all(arr);