Jogoldirus
Jogoldirus

Reputation: 3

NODEJS Getting data from database , then use them

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)

Upvotes: 0

Views: 871

Answers (1)

Tomalak
Tomalak

Reputation: 338128

  • 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);
    }
});

Upvotes: 1

Related Questions