I'm creating an API service in NodeJS using Express (version 4) Framework. Created an MVC architecture for the same (no views, only model, and controller as this is an API).
Also, there are routes. When a request is made, the router redirects the request to the controller function and from there functions written in models are called and the response is returned to users in JSON format.
I gotta make multiple asynchronous requests from the controller for some functions. I earlier nested the asynchronous calls (callback hell) before I switched to Promises.
My NodeJS version is 6.12 and it does not support async/await.
I wanna make sure the way I implemented promises is correct.
Here is a sample function from my controller using which I fetch user details. The user passes a userID and using that I fetch user details. And using details from the 1st async request, I fetch user's posts and after that, I fetch user comments. I wanna make sure my implementation is correct.
Note: I removed error handling from some asynchronous requests to make the code look more understandable.
exports.fetchUserInformation = function (req, res) {
var response = {};
if (req.query.userId) {
var userId = req.query.userId;
response['userId'] = userId;
new Promise(function (resolve, reject) {
var param = {
userId: userId
};
//1 - Call to Model function to fetch user info
User.getUserDetails(param, function (err, rows) {
if (err) {
reject(err);
} else {
resolve(rows);
}
});
}).then(function (result1) {
var result2;
response['userDetails'] = result1;
//Pass result from previous promise to fetch next result
var params1 = {
userId: userId,
result: result1
};
//2 - Call to Model function to fetch user timeline posts
User.fetchUserPosts(params1, function (err, rows) {
result2 = rows;
});
}).then(function (result2) {
response['userPosts'] = result2;
var params2 = {
userId: userId,
userType: 'user'
};
User.fetchUserComments(params2, function (err, rows) {
response['userComments'] = rows;
//return the response to user
res.json({
success: true,
response: response
});
});
}).catch(function (error) {
//error logging starts
var logData = {
stackTrace: error
};
logHlpr.logThisError(logData); //calling another function to log data
//error logging ends
res.json({
success: false
});
});
}
};
I've few doubts:
I'm making 3 async requests to the Model - User.getUserDetails, User.fetchUserPosts, User.fetchUserComments
using one promise. Should I implement 3 promises?
I'm pretty new to NodeJS and promises.
result2
get passed through from stage 2 to stage 3? \$\endgroup\$