Return promise when all records have got inserted into database node js postgress

45 Views Asked by At

I am parsing csv data and inserting into postgres using node js "pg" library. I have multiple await function to get executed. I have tried adding "Promise" to the insert , but it is not returning any promise. Where to exactly place the promise, so that i can execute rest all functions, after all data has been insertt

let csvStream = parse()
        .on("data", function (data) {
                parsedata.push(data)
        })
        .on("end", function () {
            parsedata.shift();

            const query =
                "INSERT INTO Test_Stage (EmployeeID, UID) VALUES ($1, $2)";
            var queryCount = parsedata.length;
            pool.connect((err, client, done) => {
                if (err) throw err;
                return new Promise(function (resolve, reject) {
                    parsedata.forEach(row => {
                        client.query(query, row, (err, res) => {
                            if (err) {
                                console.log(err.stack);
                                return reject(err);
                            } else {
                                queryCount--;
                                console.log(queryCount)
                                if (queryCount === 0) {
                                    return resolve('insert finished')
                                }
                            }
                        });
                    });
                });
            });
        });

    stream.pipe(csvStream);
0

There are 0 best solutions below