JN_newbie JN_newbie - 14 days ago 5
Javascript Question

Returning empty response using ES6 promise in node.js

how can I call a query using ES6 native promises in node.js. Below is the code.

let arr= [];
conn.query('select * from table1', (err, b) => {
for (let i = 0; i < b.length; i++) {
console.log(b[i]["id"])
let promiseGetData = new Promise((resolve, reject) => {
conn.query('select * from table2 where id = ?', [b[i]["id"]], (err, ce) => {
if (err) {
const response = {
statusCode: 500,
body: JSON.stringify({
message: err
}),
}
reject(response);
} else {
if (ce.length != 0) {
resolve(ce);
}
}
});
});

promiseGetData .then((data) => {
b[i]['data'] = data;
arr.push(b[i])
}).catch((err) => {
console.log(err);
});
}
console.log(b)
})


I see an empty response when i do console.log(b). I dont know if I have used a promise in correct way, I think for first query I should execute in the promise as well. Any help is very much appreciated

Answer

You got empty response from console.log(b) because the promise from querying database aren't finished. You have to wait all of them to finish before you can get the full result.

Sample:

let arr = [];
conn.query('select * from table1', (err, b) => {

  var promiseArr = [];

    for (let i = 0; i < b.length; i++) {
        let promiseGetData = new Promise((resolve, reject) => {
            conn.query('select * from table2 where id = ?', [b[i]["id"]], (err, ce) => {
                if (err) {
                    const response = {
                        statusCode: 500,
                        body: JSON.stringify({
                            message: err
                        }),
                    }
                    reject(response);
                } else {
                    if (ce.length != 0) {
                        resolve(ce);
                    }
                }
            });
        });

            promiseArr.push(promiseGetData);
    }

    Promise.all(promiseArr).then((resultArr) => {
        //resultArr is all the resolved value returned from the promise in promiseArr
        for (let i = 0; i < resultArr.length; i++) {
            b[i]['data'] = resultArr[i];
            arr.push(b[i]);
        }
    }).then(() => {
        console.log(arr);
    }).catch((err) => {
        //if any promise throw/reject with error, it will go here directly
            console.log(err);
    });
})

Edit: Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise