0

how to make this function work. Only a promise comes back to me.

codeProducts.forEach((code, index) => {

    const qt = app.db('products').where('code',code).first().then(result => result.quantity)
      data[index] = {
        code: code,
        quantity: qt
      }
    })


    return data
Fazal Rasel
  • 4,446
  • 2
  • 20
  • 31
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – str Nov 11 '18 at 11:45

2 Answers2

0
let data = codeProducts.map((code, index) => {

    return app.db('products').where('code',code).first()
    .then(result => {
        return {
        code: code,
        quantity: result.quantity
      }
    }) 
})  


return data

This code should fix your problem. You are accessing the quantity outside of the promise. In order to set the quantity on the data array, you need to do it inside the then

Pedro Silva
  • 2,655
  • 1
  • 15
  • 24
0

There is two or three ways that you can solve this-

Approach: 1

I will make just one call to database.(I love my database :D) as-

let codeProducts = [55, 68, 96];
knex('products')
    .whereIn('code', codeProducts)
    .then((results) => {
        // response to api call
        console.log(results);
    });

Approach: 2 (I don't like this approach. Too many call on db)

async function getData(codes) {
    try {
        let results = [];
        for (let i = 0; i < codes.length; i++) {
            let dbQuery = await knex('products').where('code', codes[i]).first();
            results.push(dbQuery);
        }
        return results;
    } catch (e) {
        console.log(e);
    }
}


const codeProducts = [54, 95];
getData()
    .then((res) => {
        console.log(res);
    }) 
Fazal Rasel
  • 4,446
  • 2
  • 20
  • 31