Search code examples
javascriptfunctionecmascript-6async-awaitcallback

Two functions calling each other, send message when finally done


I have 2 functions that call each other. How to send a message when all conditions are met?

My code:

const func1 = async (arg) => {
  let table_id = result.data.internal_id;
  const response = await axios_Func({ graphQL query });
  console.log(`${response.data.name} - ${table_id}`);
  return func2({ query: graphQL_query, table_id });
}

func2 = async (result, table_id) => {
  let dev = await getAllTables({ query: tables(123) });
  let prod = await getAllTables({ query: tables(321) });
  let prod_id = new Set();
  result.data.data.table.table_fields.forEach((d) => {
    if (d. connector != null && !(d.name in dev))
      prod_id.add(prod[d.name]["id"]);
  });
  prod_id = [...prod_id];
  prod_id.map((x) => createOne({ query: graphQL_query(x) });
});

const callback = () => console.log("all done");

Right now my function returns:

xyz - M5WBmnWs 
abc - QrqJ91Rq
qwe - VP0B0KEt

How do I call callback? And make my output look like this:

xyz - M5WBmnWs 
abc - QrqJ91Rq
qwe - VP0B0KEt
all done

Solution

  • I don't get exactly what you are trying to do but this should work:

    const func1 = async (arg) => {
      let table_id = result.data.internal_id;
      const response = await axios_Func({ graphQL query });
      console.log(`${response.data.name} - ${table_id}`);
      await func2({ query: graphQL_query, table_id });
    }
    
    func2 = async (result, table_id) => {
      let dev = await getAllTables({ query: tables(123) });
      let prod = await getAllTables({ query: tables(321) });
      let prod_id = new Set();
      result.data.data.table.table_fields.forEach((d) => {
        if (d. connector != null && !(d.name in dev))
          prod_id.add(prod[d.name]["id"]);
      });
      prod_id = [...prod_id];
      prod_id.map((x) => createOne({ query: graphQL_query(x) });
      // if createOne is a promise you need:
      // return Promise.all(prod_id.map((x) => createOne({ query: graphQL_query(x) }));
    });
    
    const callback = () => console.log("all done");
    
    const execute = async () => {
      await func1()
      callback()
    }