2020-11-27

NodeJS send response to client only after saving all object to DB

I have the code below, from a REST API, that inserts data in Mysql. I use Node and Express (this is, in fact, my 1st Node project, so please bear in mind I don't understand much about Node).

What I need is that response to client (browser, web application, Postman for testing or whatever access to the API) is returned only when the forEach loop and data insertion into DB terminates, so I get a JSON object with the list error messages, if any.

I've been hitting my head on the wall for half a day, and this is what I got so far.

var wait=require('wait.for');
var async = require('async');
var Promise = require('promise');
var Q = require('q');

var errmsg = [];
router.route('/subscriber').post((req, res, callback) => {
    const data = req.body; 
    
    var subscriberCollection = data;
    
    this.errmsg = [];
    
    let asyncCall =  
      (async  () => {
            let rr = await new Promise (resolve => subscriberCollection.forEach(function (value, key){      
                    
                    var phoneNumber = value.phoneNumber;
                    var msg = "";
                    if (phoneNumber == ""){
                        msg = "ERROR","missing phoneNumber for subscriber index #" + key + ";Skipping";
                        console.log(msg);
                        errmsg[key] = msg
                        return;
                    }
                    
                    var sql = "call insertSubscriber(?)";           
                    console.log("INFO",`Inserting subscriber ${phoneNumber} index ${key}`);
                        
                        connection.query(sql,[ phoneNumber ] ,function (err, data) {            
                            if (err){ 
                                var msg = err.errno + " - " + err.sqlMessage;
                                console.log("ERROR" , msg);
                                errmsg[key] = msg;
                            }
                        });
                        
                }) //end forEach
            ); //end Promise    
    })();
    
    asyncCall.then(console.log("ENDING!!") ); // THIS IS NOT WORKING

});

On the console, I get this:

INFO Inserting 916311145 for index 0
INFO Inserting 916311146 for index 1
ENDING!!
ERROR 1062 - Duplicate entry '916311145' for key 'phoneNumber_UNIQUE'
ERROR 1062 - Duplicate entry '916311146' for key 'phoneNumber_UNIQUE'

but what I need it to be is:

INFO Inserting 916311145 for index 0
INFO Inserting 916311146 for index 1
ERROR 1062 - Duplicate entry '916311145' for key 'phoneNumber_UNIQUE'
ERROR 1062 - Duplicate entry '916311146' for key 'phoneNumber_UNIQUE'
ENDING!!

Also, when all subscriber objects are saved on DB, I need to return a response to client, something like:

[{"key 0" : "ok"},{"key 1" : "ok"}, {"key 3": "ERROR 1062 - Duplicate entry '916311145' for key 'phoneNumber_UNIQUE'"}...]

and again, the response should only appear when all processing has finished. How can I get this work?



from Recent Questions - Stack Overflow https://ift.tt/3fBYm4b
https://ift.tt/eA8V8J

No comments:

Post a Comment