Martin Martin - 6 months ago 27
MySQL Question

Promise to do something after all rows from MySQL result are processed

Thanks in advance. I'm trying to do something after all rows from MySQL result is processed. I tried with Promises but It's not working.
Theres 4600 rows but I'm just getting []. I'm guessing my issue is NodeJS Async.
Here is my code:

let paradasRelations = db.query('SELECT * FROM ParadasRelations');

let paradaPromise = new Promise(function (resolve, reject) {
let paradasData = [];
paradasRelations.on('result', function (row) {
paradasData.push(row);
});
resolve(paradasData);
});
paradaPromise.then(function (paradasData) {
console.log(paradasData);
});

Answer

You need to resolve the Promise only after all the rows have been returned and you get an end event. This is untested but something like this should work:

let paradasRelations = db.query('SELECT * FROM ParadasRelations');

let paradaPromise = new Promise(function (resolve, reject) {
    let paradasData = [];
    paradasRelations.on('result', function (row) {
        paradasData.push(row);
    });

    paradasRelations.on('end', function () {
        resolve(paradasData);
    });
});

paradaPromise.then(function (paradasData) {
    console.log(paradasData);
});