Good, I tell you my question:
I have a function in node.js
that what it does is to collect all the clients of a database SQL
. I am using the mssql
package for this but the issue is that for each client I must make another request to add more data to each of them. The problem is that the request is asynchronous and does not wait to receive the answer to continue with the next one, here the example:
exports.getClients = function(req, res) {
var response = []
new sql.Request()
.execute('getClients')
.then(function(clientes) {
var clientesArray = clientes[0]
for (var i = 0; i < clientesArray.length; i++) {
new sql.Request()
.execute('getDireClients')
.then(function(dirents) {
//aquí es donde se añaden los datos a un cliente
}).catch(function(err) {
res.json({
"error": err.message
})
});
}
}).catch(function(err) {
res.json({
"error": err.message
})
});
};
How have I solved it? Well, doing a recursive function that would go through the array of clients by an index and once said index is equal to the size of the array that returns the response. (Share if it helps someone)
exports.getClients = function(req, res) {
var response = []
var addedClientsCount = 0
new sql.Request()
.execute('getClients')
.then(function(clientes) {
var clientesArray = clientes[0]
addDirentsToClient(clientesArray , addedClientsCount, res, response)
}).catch(function(err) {
res.json({
"error": err.message
})
});
};
function addDirentsToClient (clients, addedClientsCount, res, response) {
new sql.Request()
.execute('getDireClients')
.then(function(dirents) {
if (addedClientsCount >= clients.length) {
res.json(response)
}else{
//aquí añado los datos al cliente, he suprimido
// esta parte porque es larga
response.push(clients[i])
addedClientsCount = addedClientsCount + 1
addDirentsToClient(clients, addedClientsCount, res, response)
}
}).catch(function(err) {
res.json({
"error": err.message
})
});
}
Then my question is:
Can this be done but with the first example, that is, with a for?