0

i want to get data from database and array-loop That's my actual structure. I have already test a tons of things without success

app.get('/url' async (req,res)=> {
    value = []
    async function myFunction(){
    
        myArray.map(async(data)=> {
            db('MY QUERY')
            .then((res)=> {
                value.push(res)
            })
        })
    }
    await myFunction()
    console.log(value) // Always empty
})

I'm open to any tips from you ! :)

EDIT : More information about database connection: myArray is like : ["a","*","b","myOwnMathFunction(a)"] but not important here Query : "SELECT * FROM User WHERE id='1' " //Verified & work

const bd = mysql.createConnection({ MY CONFIG})
    const db =  util.promisify(bdd.query).bind(bdd)
5
  • 2
    Please refer to this stackoverflow.com/questions/40140149/… Commented May 21, 2021 at 10:19
  • What is your SQL query? And provide some more code related to database connection and all. Commented May 21, 2021 at 11:07
  • @zx01 My SQL query work & my database connection work too , i only have problem with async notion. I added more informations on the post Commented May 21, 2021 at 11:18
  • Yeah I understand but you need to give some context like what is myArray here? Commented May 21, 2021 at 11:21
  • @zx01 that's an array of math operator & maded functions used in my loop Commented May 21, 2021 at 11:31

1 Answer 1

1
  • Use Array#map() to create multiple promises, e.g. from database queries.
  • Use Promise.all() to wait for multiple promises.
  • Use try/catch to handle success and error.

i.e.

app.get('/url', async (req, res) => {
    try {
        const sql = 'SELECT * FROM mytable WHERE x = ? AND y = ? AND z = ?';
        const queries = myArray.map((item) => database.query(sql, [item.x, item.y, item.z]));
        const results = await Promise.all(queries);
        res.send(results);
    } catch (err) {
        console.error(err.stack);
        res.status(500).send(err);
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

It work really well , thanks ! I saw this but didn't understand how to use it , thanks for your explanation of each things
@Jogoldirus If it works well and you're using it, please tick the answer as "accepted". This will close the thread.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.