I am little bit struggling in handling the asynchronus calls on queries, how can I get the response in proper order.
I have a user array, it has a payload of json objects, what I want to do is inserting the user and its details in different tables such as emails, pictures etc. Below is my pseudo code snippet
var jsonObj = {};
var jsonArray = [];
for (var i = 0; i < userArray.length; i++) {
var userJSON = userArray[i];
if (typeof userJSONJSON.list_of_emails != 'undefined') {
conn.query('insert into user_tble set ?', userJSON, function (err, ins) {
conn.query('insert into user_emails (user_id,email_address,) values ?', [globalEmailAddressArray], function (err, ins2) {
conn.query('insert into user_phones (user_id,phone_number) values ?', [globalPhoneNumberArray], function (err, ins3) {
conn.query('insert into user_pictures (user_id,pic_url) values ?', ['http://localhost:300/somepicture'], function (err, ins4) {
jsonObj["result"] = "executed1";
jsonArray.push(jsonObj);
res.status(200).json(arr: jsonArray)
})
})
})
});
} else if (typeof userJSONJSON.list_of_phones != 'undefined') {
conn.query('insert into user_phones (user_id,phone_number) values ?', [globalPhoneNumberArray], function (err, ins3) {
conn.query('insert into user_pictures (user_id,pic_url) values ?', ['http://localhost:300/somepicture'], function (err, ins4) {
jsonObj["result"] = "executed2";
jsonArray.push(jsonObj);
res.status(200).json(arr: jsonArray)
})
})
}
}
if i give a payload something like
{
"pay_load":[
{
"list_of_emails": [
{"email":"user1@user1.com"}
],
"last_name": "",
"first_name": "User1"
},
{
"list_of_email_addresses": [
{"email":"user2@user2.com"}
],
"last_name": "",
"first_name": "User2"
},
{
"list_of_email_addresses": [],
"last_name": "",
"first_name": "User3"
}
]
}
If I execute the json code it returns e.g it returns me the output
{
arr:[
{
result : "executed2"
}
]
}
I want something like due to to asynchronous nature i think it skips out the remaining two.
{
arr:[
{
result : "executed1"
},
{
result : "executed1"
},
{
result : "executed2"
}
]
}
In short how can I handle the asynchronous calls to achieve the above output.