0

I have recently started learning node.js and for that purpose started converting one of my php projects.

I am trying to understand how async and await works, but cannot seem to find a solution on my own and would appreciate some help.

I have following function

exports.getTypes = async (req, res) => {

    var categories = [];

    pool.query('call livestockGetTypeAll()', [], 
        await function(err, results, fields) {
              
            if (err) throw err;

            //return res.json(results[0]);
            categories = JSON.parse(JSON.stringify(results[0]));     

            for(let i = 0; i < categories.length; i++){
                
                req.body.id = categories[i].id;                      
                categories[i].sub_items = exports.getSubTypes(req, res);
            }

            return res.json(categories);      
        }
    );  
};

This function is supposed to call another one and populate sub_items

exports.getSubTypes = async (req, res) => { 
        
    pool.query('call livestockGetSubTypeAll(?)', 
        [
            req.body.id
        ], 
        await function(err, results, fields) {
              
            if (err) throw err;

            //return res.json(results[0]);
            return results[0];
        }
    );  
};

But it seem to return categories from the first function without waiting for any response to populate sub_items.

I would really appreciate help on this one.

Dmitris
  • 3,408
  • 5
  • 35
  • 41
  • What is `pool.query`? You should use a promise+`await` there, not a callback. – Bergi Mar 14 '23 at 22:36
  • You only really *need* async / await whenever you're dealing with promises. Does `pool.query` return a `Promise` object? – Emiel Zuurbier Mar 14 '23 at 22:36
  • pool query is mysql query that calls on stored procedure and returns selection – Dmitris Mar 14 '23 at 22:37
  • `await function(…) {}` is pointless, a function is not a promise. This won't make the code wait until the function was called or something. What you *do* need to `await` though is the `exports.getSubTypes(req, res)` call. – Bergi Mar 14 '23 at 22:38
  • @EmielZuurbier I tried to remove all async awaits in both functions, and it still doesn't wait for returns from second function – Dmitris Mar 14 '23 at 22:38
  • Do yourself a favour and don't use `mysql` but rather `mysql-promise` or `mysql2`. – Bergi Mar 14 '23 at 22:41
  • @Bergi It is mysql2 – Dmitris Mar 14 '23 at 22:45
  • 1
    Then you should simply use `const [rresults, field] = await pool.query('call livestockGetTypeAll()', []);`. See https://www.npmjs.com/package/mysql2#using-promise-wrapper – Bergi Mar 14 '23 at 22:47

0 Answers0