Fetching Multiple Https request in Nodejs using ejs templates - node.js

Getting the first [ const p1] HTTPS request, but unable to fetch the second one [const p2] its showing me undefined.Where im missing
function fetchJSON(url) {
return new Promise((resolve, reject) => {
request(url, function(err, res, body) {
if (err) {
reject(err);
} else if (res.statusCode !== 200) {
reject(new Error('Failed with status code ' + res.statusCode));
} else {
resolve(JSON.parse(body));
}
});
});
}
router.get('/news-and-media',function(req,res,next){
const p1 = fetchJSON('http://example.com/wsplus/abs/123');
const p2 = fetchJSON('http://example.com/blsd/blog_posts/312');
Promise.all([p1],[p2]).then((data) => {
console.log(data[0]); // getting data
console.log(data[1]); // this giving me undefined
res.render("news-and-media", { getdata: data[0],banner:data[1]} );
}).catch(err => console.error('There was a problem', err));
});

Don't use
Promise.all([p1], [p2])
but
Promise.all([p1, p2])
According to the Promise.all() documentation which is saying :
Promise.all(iterable);

Related

Adding async await in node js

I am using node js function i have written the code long before but i need to add async and await in my functions i don know how to proceed with my code structure .
Here is my code structure
app.express.get('/api/member/logout', function (request, response) {
functionBal.logout(request.query.abc).then(function (result) {
if (result) {
response.set('Content-Type', 'application/json');
response.status(200);
response.json(result);
}
}).catch(function (err) {
response.set('Content-Type', 'application/json');
response.status(400);
response.json("Error -- " + err);
});
});
module.exports.log = function (abc) {
return new app.promise(function (resolve, reject) {
functionDal.log(abc).then(function (result) {
if (result)
resolve(result);
else {
reject("Error");
}
}).catch(function (err) {
reject(err);
});
})
};
module.exports.log = function (abc) {
return new app.promise(function (resolve, reject) {
mySqlConnection.connection().then(function (con) {
con.query("UPDATE member SET table1 = 0 WHERE abc = ?", [abc]).then(function (rows, fields) {
resolve('success');
}).catch(function (err) {
reject(err);
});
}).catch(function (err) {
reject(err);
});
});
}
Please help in adding async await in this coding structure
Give this is try.
app.express.get('/api/member/logout', async function (request, response) {
try {
let data = await functionBal.logout(request.query.abc)
response.set('Content-Type', 'application/json');
response.status(200);
response.json(result);
} catch (error) {
response.set('Content-Type', 'application/json');
response.status(400);
response.json("Error -- " + err);
}
});
module.exports.log = async function (abc) {
try {
return await functionDal.log(abc)
} catch (error) {
throw error
}
};
module.exports.log = async function (abc) {
try {
const con = await mySqlConnection.connection()
await con.query("UPDATE member SET table1 = 0 WHERE abc = ?", [abc])
return 'success'
} catch (error) {
throw error
}
}
Make sure, you have Node.js 8+.

how to return results to postman using nodejs.i couldn't send result

App.js
app.get('/getCus', function (req, res) {
var id= req.query;
cus_controller.getCus(id,function(response) {
res.json(response);
});
});
cus_controller.js:
module.exports ={
getCus: function (id, callback) {
getCus = function () {
getOneCus(id).then(result => {
callback(result);
}).catch(err => {
callback(err)
})
}
process.nextTick(getCus);
},
}
async function getOneCus(id) {
auth.authClient(function (err, client) {
if (client) {
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
getCus(id,client, callback);
}
else {
console.error(err);
}
})
}
var getCus = (id, client, callback) => {
client
.invokeApi(null, `/cus/${id}`, 'GET')
.then(function (result) {
console.log(result.data);
return result.data
})
.catch(function (result) {
if (result.response) {
console.dir({
status: result.response.status,
statusText: result.response.statusText,
data: result.response.data
});
} else {
console.log(result.message);
}
});
}
in getCus method getting a response in the console. however, couldn't get a response in postman.it shows 200 status code but didn't get a response. Someone help me, please. I could not find any solution for this.i tried many methods like return data and res.send(data).
You're passing a callback function to getCus, but you never use it. It looks like you meant call it instead of return the result:
client
.invokeApi(null, `/cus/${id}`, 'GET')
.then(function (result) {
console.log(result.data);
callback(result.data); // <-- here
})
Alternatively, if you return the result as you currently do, then you wouldn't pass a callback to getCus but would instead use a .then() structure:
cus_controller.getCus(id).then(function(response) {
res.json(response);
});
But be sure to also return the top-level Promise by returning the call to client.invokeApi:
return client // <-- here
.invokeApi(null, `/cus/${id}`, 'GET')
.then(function (result) {
console.log(result.data);
return result.data
})

Dealing with multiple error checks in NodeJS controller

I need to validate multiple checks in my controller and throw possible errors to my route. Something like this:
Router:
send post var to controller
Controller:
throw error if post.categoria is blank
check in mysql if already exists
throw error if already exists
Router code:
// POST new
router.post('/', function(req, res, next){
// get post var
var post = {categoria: req.body.categoria};
// validate
controller.newCategoria(post).then(
result => {
// return valid result, I'll implement it later
res.json(result);
},
error => {
// return error to frontend
res.json(error);
}
);
});
Controller code:
module.exports.newCategoria = async (post) => {
// throw error if blank
if (post.categoria.length == 0)
throw "categoria is empty"; // portuguese
db.query('SELECT COUNT(id) AS count FROM categoria WHERE ?', post, function(err, result) {
if (err)
throw err;
if (JSON.stringify(result[0].count) >= 1)
throw new Error("already exists");
});
return "ok";
};
If I send and existing categoria I get: Rethrow non-MySQL errors
I tried to use a promise:
module.exports.newCategoria = async (post) => {
// check if blank
if (post.categoria.length == 0)
throw "blank categoria";
new Promise((resolve, reject) => {
db.query('SELECT COUNT(id) AS count FROM categoria WHERE ?', post, function(err, result) {
if (err)
return reject(err);
if (JSON.stringify(result[0].count) >= 1)
return reject(new Error("already exists"));
return resolve(result);
});
}).then(
resolve => {
// ok.. deal with it
console.log('ok');
console.log(resolve);
},
error => {
throw error;
}
).catch((error) => {
throw error;
});
return "ok";
};
I don't know how to throw it back to rote, I'm getting this error:
UnhandledPromiseRejectionWarning: Error: already exists
I'm new to NodeJS, I need a good practice for it. Thanks.
You need to return a Promise like so
module.exports.newCategoria = async (post) => {
return new Promise((resolve, reject) => {
// throw error if blank
if (post.categoria.length == 0)
reject(new Error("categoria is empty")); // make sure you are throwing Errors or else node will chastise you
db.query('SELECT COUNT(id) AS count FROM categoria WHERE ?', post, function(err, result) {
if (err)
reject(err);
else if (Number(result[0].count) >= 1) // compare ints to ints, not string to int
reject(new Error("already exists"));
else
resolve(result)
});
})
};
If you want to do more async stuff, here is one way you could refactor
const alreadyExists = x => x && x[0] && x[0].length > 1
const getCategoria = post => {
return new Promise((resolve, reject) => {
db.query(
'SELECT COUNT(id) AS count FROM categoria WHERE ?',
post,
(err, result) => {
if (err)
reject(err)
else if (alreadyExists(result))
reject(new Error('already exists'))
else
resolve(result)
},
)
})
}
module.exports.newCategoria = async post => {
const categoria = await getCategoria(post)
// insert here
}

Nodejs Promise "res.end is not a function" error

I'm refactoring my code to remove a "callback hell" using Promises, but encountered an error that I cannot pass. My code receives list of IDs and processes them making few database calls, that is why I had this "callback hell".
Everything worked fine until Promises. The res is equal 0 when I had to respond back to the client.
function processVMDelete(returnedVMIDs){
return new Promise((resolve, reject) => {
var mariasqlClient = dbConnection();
mariasqlClient.query( sqlUpdateDELETE_STATE_ByVMID, [
'DELETE',
returnedVMIDs
], function(err, rows) {
if (err){
reject(err);
}
console.log('finish update');
// dont' need to return anything here
resolve(0);
});
mariasqlClient.end();
});
}
function getListExpVM(){
return new Promise((resolve, reject) => {
var vmList = [];
var mariasqlClient = dbConnection();
mariasqlClient.query( sqlSearch_ByUSERNAMEAndSTATE, [
requesterUsername,
'ACTIVE'
], function(err, rows) {
if (err){
reject(err);
}
vmList = filterExpiredVMs(rows);
var response = {
status : 200,
success : 'Successfull',
data : vmList,
requester: requesterUsername
};
resolve(response);
});
mariasqlClient.end();
});
}
router.post('/processVMs', function(req, res) {
var returnedVMIDs = JSON.parse(req.body.data);
processVMDelete(returnedVMIDs)
.then(res => {
console.log('done');
// check if there is more available for the user:
getListExpVM()
.then(response => {
console.log('sending back list of VMs');
//===>>> ERROR HERE: res.end is not a function
res.end(JSON.stringify(response));
})
.catch(err => {
console.log('error', err.message);
logger.error("Error getting expired VMs: " + err.message);
//===>>> ERROR HERE: res.send is not a function
res.status(500).send({error: err.message})
});
})
.catch(err => {
console.log('error', err.message);
logger.error("Error processing VMs: " + err.message);
//===>>> ERROR HERE: res.send is not a function
res.status(500).send({error: err.message})
});
});
You've redefined res with this:
processVMDelete(returnedVMIDs)
.then(res => {...})
This will hide the higher scoped res associated with the overall request (the one you need to use for res.end()). Change the name of this one to something else like result and then change the corresponding references that use this result.

Express js promise.all returns undefined

Hi i am newbie to express and promise, i am trying to call multiple asynchronous function using promise.all from express router, but it returns undefined, please guide me to solve the issue .
user.js //routes
var findAllUsersDetails = function(router){
router.post('/api/v1/users/getAllUserFormDetails',
function (req, res) {
Promise.all([
userModel.getAllUsers(req),
userModel.getAllUsers(req),
])
.then((data) => console.log(data))
.catch((err) => console.log(err))
});
}
user.js // models
var userModel = {
getAllUsers : function(req){
var string = "";
var id_company = req['user'].id_company;
var dbConnection = dbConnectionCreator();
var getAllUsers = getAllUsersSqlString(string, id_company);
console.log("ANGEL: finding all employees");
dbConnection.query(getAllUsers, function(error, results, fields){
return new Promise((resolve, reject) => {
console.log(results);
if (error) {
dbConnection.destroy();
console.log("error: ", error);
return reject (err);
} else if (results.length === 0) {
resolve("User not found.");
} else {
resolve(results);
//return (callback({employeeData: results}));
}
})
});
},
}
module.exports = userModel;
Your getAllUsers function is expected to return Promise, but is returning undefined(nothing).
The promise is returned to dbConnection.query but not to the getAllUsers function.
You can try adding return.
return dbConnection.query
if this doesn't work, then dbquery doesn't return the callback which was returned to it.
You might need to find an alternative to solve this.
Let me know if it works.
userModel.getAllUsers(req) should return Promise a.e.:
function getAllUsers(req) {
return new Promise(function(resolve, reject){
//...
});
}
In your case dbConnection.query(getAllUsers, function(error, results, fields) returns Promise therefore you can write something like:
getAllUsers : function(req){
var string = "";
var id_company = req['user'].id_company;
var dbConnection = dbConnectionCreator();
var getAllUsers = getAllUsersSqlString(string, id_company);
console.log("ANGEL: finding all employees");
return dbConnection.query(getAllUsers, function(error, results, fields){
// ^^^
return new Promise((resolve, reject) => {
console.log(results);
if (error) {
dbConnection.destroy();
console.log("error: ", error);
return reject (err);
} else if (results.length === 0) {
resolve("User not found.");
} else {
resolve(results);
}
})
});
},
What i did is i placed the dbconnection within promise function and now i can return promise with the results of dbConnection.query()
getAllUsers : function(req){
var string = "";
var id_company = req['user'].id_company;
var dbConnection = dbConnectionCreator();
var getAllUsers = getAllUsersSqlString(string, id_company);
console.log("ANGEL: finding all employees");
return new Promise((resolve, reject) => {
dbConnection.query(getAllUsers, function(error, results, fields){ //
console.log(results);
if (error) {
dbConnection.destroy();
console.log("error: ", error);
return reject (err);
} else if (results.length === 0) {
resolve("User not found.");
} else {
resolve(results);
//return (callback({employeeData: results}));
}
});
});
Thanks for your immediate reply, actually i understood issue is because of returning promise from your answers.

Resources