1

I have a promise for getting data from a mysql database using mysql2 on express. I need to get data from the first query into the final returned object after running another query.

db.query("SELECT * FROM users_tasks_link WHERE uin = ?", [req.params.id])
        .then(result => {
            const foo = db.query(
                "SELECT * FROM tasks WHERE id IN (?); SELECT * FROM headers; SELECT * FROM categories; SELECT * FROM links",
                [
                    result[0].map(e => {
                        return e.task_id;
                    })
                ]
            );
            return foo;
        })
        .then(foo => {
            let tasks = [];
            foo[0][0].forEach(element => {
                let task = {
                    id: element.id,
                    title: element.title,
                    header: foo[0][1].filter(e => element.header === e.id)[0].header,
                    category: foo[0][2].filter(e => element.category === e.id)[0].category,
                    notes: element.notes,
                    level: element.level,
                    links: foo[0][3]
                        .filter(e => element.id === e.task_id)
                        .map(el => {
                            return {
                                name: el.name,
                                link: el.link
                            };
                        })
                };

                tasks.push(task);
            });
            return res.send({ data: tasks, message: "Got all tasks for user" });
        })
        .catch(err => {
            console.log(err);
        });

I need a value from "result" in the tasks object, but I can't access the result data from "foo".

Dom Needham
  • 69
  • 1
  • 14

1 Answers1

2

Create a variable higher in scope before calling db.query. And store the results in it to be referenced later:

var datavar;

db.query("SELECT * FROM users_tasks_link WHERE uin = ?", [req.params.id])
    .then(result => {
        datavar = result;
        const foo = db.query(
            "SELECT * FROM tasks WHERE id IN (?); SELECT * FROM headers; SELECT * FROM categories; SELECT * FROM links",
            [
                result[0].map(e => {
                    return e.task_id;
                })
            ]
        );
        return foo;
    }).then(foo => { // You can now use datavar to access the data you want }
silencedogood
  • 3,209
  • 1
  • 11
  • 36
  • So simple, but it works! Thank you. Wasn't sure if it was considered 'best practice' or not. – Dom Needham Sep 10 '19 at 13:55
  • @DomNeedham Well, if this is considered bad practice, I'm currently unaware :) Although who knows, maybe someone has some superior solution I've yet to see. Needless to say, I think you're safe. – silencedogood Sep 10 '19 at 13:59