why is that ReferenceError: err is not defined even though it is defined here?
const sampleObject = require('./sampleObject');
const sampleModel = (callback) => {
if (true) {
sampleObject.sampleRetrieval(err, data => {
if (err) {
callback(err)
} else {
callback(data)
}
})
} else {
console.log('Something went wrong.');
}
}
module.exports = sampleModel;
This is the file that executes the query and passes it to the sampleModel.
const myDB = require('../db/database');
module.exports = {
sampleRetrieval: () => {
let sql = "SELECT * FROM ACCOUNTS";
myDB.query(sql, (err, data) => {
if (err) {
callback(null, err)
} else {
callback(err, data)
}
})
}
}
Error : err is not defined
newUser.save()
.then( ()=> res.json('User added!'))
.catch( err => res.status(400).json('Error: '+ err));
Fixed
newUser.save()
.then( ()=> res.json('User added!'))
.catch( (err) => res.status(400).json('Error: '+ err));
The problem is that your function sampleRetrieval is not receiving a callback function as a parameter. It should be something like this:
sampleRetrieval: (callback) => {
let sql = "SELECT * FROM ACCOUNTS";
myDB.query(sql, (err, data) => {
if(err) {
callback(null, err);
} else {
callback(err, data);
}
})
}
And then fix the parentheses like the comment of Dan O says:
const sampleModel = (callback) => {
if (true) {
sampleObject.sampleRetrieval((err, data) => {
if (err) {
callback(err)
} else {
callback(data)
}
})
} else {
console.log('Something went wrong.');
}
}
Hope it helps!
Related
I'm new to Javascript. I want to make this block run after the if statement is finished (asynchronous). The reason I want that is that I want to make some changes to update them if it falls into the if statement
let params = {
TableName: "storepedia-test",
Item: updatedItem
};
docClient.put(params, function (err, data) {
if (err) {
console.log(err);
} else {
res.redirect('/devices');
}
});
Here is my whole code
const { id } = req.params;
const file = req.file;
let updatedItem = { ...req.body};
updatedItem.id = id;
if (file !== undefined){
const deleteParams = {
Key: updatedItem.image,
Bucket: bucketName
}
s3.deleteObject(deleteParams, async (err, data) => {
if (err) {
console.log(err)
} else {
const result = await uploadFile(file);
console.log('result', result);
await unlinkFile(file.path);
updatedItem.image = result.Key;
let params = {
TableName: "storepedia-test",
Item: updatedItem
};
docClient.put(params, function (err, data) {
if (err) {
console.log(err);
} else {
res.redirect('/devices');
}
});
}
})
}
let params = {
TableName: "storepedia-test",
Item: updatedItem
};
docClient.put(params, function (err, data) {
if (err) {
console.log(err);
} else {
res.redirect('/devices');
}
});
Just to run something after the if? I think this is the best spot:
docClient.put(params, function(err, data) {
if (err) {
console.log(err);
} else {
// run async code here.
// when done do the redirect.
// for example:
s3.do_something(function(err, data) {
if (err) {
console.log(err)
} else {
console.log(data)
res.redirect('/devices');
}
})
}
});
I'm in a situation where I have a POST route that calls a function multiple times. I want the request to return an error if the called function returns an error, but I am not sure how to achieve this. See this image:
This is my code:
function POSTcord(lat, lng) {
axios
.post(process.env.SOS_POST_URL + process.env.SOS_POST_CODE, {
batteryLevel: 100,
longitude: lng,
latitude: lat
})
.then(res => {
console.log(`statusCode: ${res.status}`)
})
.catch(error => {
console.error(error.message);
})
}
router.post('/test', async (req, res) => {
let passedCords = req.body;
try {
for (const cord of passedCords) {
POSTcord(cord.lat, cord.lng);
}
res.status(200).json({status:"success", message: "hello!"});
} catch (err) {
console.error(err.message);
res.status(500).send("Server error");
}
});
I want the route /test to return an error if the function POSTcord catches an error somewhere in the loop. Any ideas on this? I'm thinking I could pass res to POSTcord function, but that didn't work. Thankful for any input :)
You need to return the Promise and make sure the error is thrown/rejected:
Either do this:
function POSTcord(lat, lng) {
return axios // <--------------- THIS IS VERY IMPORTANT
.post(process.env.SOS_POST_URL + process.env.SOS_POST_CODE, {
batteryLevel: 100,
longitude: lng,
latitude: lat
})
.then(res => {
console.log(`statusCode: ${res.status}`)
})
.catch(error => {
console.error(error.message);
throw error; // <----------- ALSO DO THIS
})
}
Or do this:
function POSTcord(lat, lng) {
return axios // <--------------- THIS IS VERY IMPORTANT
.post(process.env.SOS_POST_URL + process.env.SOS_POST_CODE, {
batteryLevel: 100,
longitude: lng,
latitude: lat
})
.then(res => {
console.log(`statusCode: ${res.status}`)
})
// DON'T CATCH THE ERROR!!
}
Then all you need to do is await to get the error:
router.post('/test', async (req, res) => {
let passedCords = req.body;
try {
for (const cord of passedCords) {
await POSTcord(cord.lat, cord.lng); // DO THIS FOR CATCH TO WORK
}
res.status(200).json({status:"success", message: "hello!"});
} catch (err) {
console.error(err.message);
res.status(500).send("Server error");
}
});
If you want to call POSTcord() in parallel you can await using Promise.all():
router.post('/test', async (req, res) => {
let passedCords = req.body;
try {
let promises = [];
for (const cord of passedCords) {
let p = POSTcord(cord.lat, cord.lng);
promises.push(p);
}
await Promise.all(promises); // DO THIS FOR CATCH TO WORK
res.status(200).json({status:"success", message: "hello!"});
} catch (err) {
console.error(err.message);
res.status(500).send("Server error");
}
});
I am using async parallel to get data from db in parallel.
When every task is returning the data I am storing it in local object.
From index.js I am calling cacheService.js .
In cacheService.js I am loading data from mysql database and mongo database in to cache object.
Whenever I am doing npm run local run. I am getting following error.
UNHANDLEDREJECTION Error: Callback was already called.
This error is coming from loadMongoData method of cacheService.js.
I have followed other answers on stackoverflow like adding else part
Here is code for cacheService.js.
'use strict';
var cache = [];
class cacheService {
async init() {
await this.loadMongoData();
}
loadMongoData(env, callback1) {
const _this = this;
console.log('Inside loadMongoData')
async.parallel(
{
task1: function (callback) {
CriteriaDef.find({})
.lean()
.exec(function (err, criteriaDefs) {
if (err) {
console.log('Inside err 1')
logger.error('Error fetching CriteriaDef: ', util.inspect(err));
callback(err, null);
} else if (criteriaDefs) {
console.log('Inside criteriaDefs')
if (criteriaDefs.length && criteriaDefs.length > 0) {
console.log('Inside criteriaDefs 1')
global.CRITERIA_DEFS = criteriaDefs;
cache['criteria_defs'] = criteriaDefs;
}
callback(null, null);
}
});
},
task2: function (callback) {
groupDef
.find({})
.lean()
.exec(function (err, groupDefs) {
if (err) {
console.log('Inside err2')
logger.error('Error fetching groupDefs: ', util.inspect(err));
callback(null, err);
} else if (groupDefs) {
console.log('Inside ')
global.groupDefsWithRoles = groupDefs;
let _groupDefs = [];
_.each(groupDefs, function (groupDef) {
var data = {
value: groupDef._id,
label: `${groupDef._id}: ${groupDef.description}`
};
_groupDefs.push(data);
});
global.groupDefs = _groupDefs;
cache['groupDefs'] = _groupDefs;
logger.info('Loaded groupDefs: ', global.groupDefs.length);
callback(null, null);
}
});
},
task3: function (callback) {
jiraProjects.find({$or: [{archived: {$ne: true}}, {archived: {$exists: false}}]}).exec(function (err, jiraProjects) {
if (err) {
console.log('Inside error 3')
logger.error('Error fetching jiraProjects: ', err);
callback(null, err);
} else if (jiraProjects) {
console.log('Inside jira project')
let _jiraProjects = [];
_.each(jiraProjects, function (jiraProject) {
var data = {
value: jiraProject.key,
label: jiraProject.key,
issueType: jiraProject.issueType ? jiraProject.issueType : 'Bug'
};
_jiraProjects.push(data);
});
global.jiraProjectsList = _jiraProjects;
cache['jiraProjects'] = _jiraProjects;
logger.info('Loaded jira projects: ', global.jiraProjectsList.length);
callback(null, null);
}
});
},
task4: function (callback) {
console.log('Inside task4')
callback(null, null);
},
task5: function (callback) {
inputElements
.find({})
.lean()
.exec(function (err, inputElements) {
if (err) {
console.log('Inside error5')
logger.error('Error fetching inputElements: ', util.inspect(err));
callback(null, err);
} else if (inputElements) {
console.log('Inside inputelements')
global.INPUT_ELEMENTS_DEF = inputElements;
cache['INPUT_ELEMENTS_DEF'] = inputElements;
callback(null, null);
}
});
},
task6: function (callback) {
console.log('Inside task6')
sisp.loadProducts('', callback);
}
},
function (err, results) {
if (err) {
console.log('Inside final error')
logger.error("Something went wrong can't start the app: ", util.inspect(err));
callback1(null, err);
} else {
console.log('Inside final else')
logger.info('loaded all globals properly :)');
callback1(null, null);
}
}
)
}
}
export default new cacheService();
I think your problem cuz you use callback inside of promise.
Please change your code like this:
class cacheService {
async init() {
await new Promise((resolve, reject) => {
this.loadMongoData(env, (ignoreArg, error) => {
if (error) {
return reject(error);
}
resolve();
});
});
}
...
}
Tip: in the each task add statement else for call callback, because maybe your statement not handled and your code can't execute prefect
task1: function (callback) {
CriteriaDef.find({})
.lean()
.exec(function (err, criteriaDefs) {
if (err) {
console.log('Inside err 1')
logger.error('Error fetching CriteriaDef: ', util.inspect(err));
callback(err, null);
} else if (criteriaDefs) {
console.log('Inside criteriaDefs')
if (criteriaDefs.length && criteriaDefs.length > 0) {
console.log('Inside criteriaDefs 1')
global.CRITERIA_DEFS = criteriaDefs;
cache['criteria_defs'] = criteriaDefs;
}
callback(null, null);
} else {
callback(null, null);
}
});
},
What is the proper way to get the result of this MySQL Query out of GetAllFarms and into a variable called err and farms? Sorry, doing a quick code try and coming from a different language.
var err, farms = GetAllFarms()
console.log("GetAllFarms:")
console.log(farms)
console.log(err)
function GetAllFarms(callback) {
query = db.query("SELECT * FROM farms ", function (err, result) {
console.log("DEBUG:QUERY//");
console.log(query.sql);
// console.log(result)
if (err) {
// console.log(err)
return callback(err, null)
} else {
// console.log(result)
return callback(null, result)
}
});
// db.end()
console.log("query")
console.log(query.result)
return query
}
Any help is much appreciated. Thanks
You have to decide wether you want to provide result via callback or with return. Don't mix them, it's confusable.
Callback approach
var err, farms = GetAllFarms()
console.log("GetAllFarms:")
console.log(farms)
console.log(err)
function GetAllFarms(callback) {
query = db.query("SELECT * FROM farms ", function (err, result) {
console.log("DEBUG:QUERY//");
console.log(query.sql);
// console.log(result)
if (err) {
// console.log(err)
return callback(err, null)
} else {
// console.log(result)
return callback(null, result)
}
});
// db.end()
console.log("query")
console.log(query.result)
}
// usage
GetAllFarms((error, result) => {
if (error) {
// handle error
}
// process result
})
Promise approach
var err, farms = GetAllFarms()
console.log("GetAllFarms:")
console.log(farms)
console.log(err)
function GetAllFarms() {
return new Promise((resolve, rejct) => {
db.query("SELECT * FROM farms ", function (err, result) {
console.log("DEBUG:QUERY//");
console.log(query.sql);
if (err) {
return reject(err)
} else {
return resolve(result)
}
});
});
}
// usage
(async () => {
const res = await GetAllFarms();
// or
GetAllFarms().then(/* ... */).catch(/* ... */);
})
How To Convert This Function to Chaining with then and catch?
Is better to Chained?
I mean User.findOne().then().catch()
User.findOne({_id: msg.chat.id}, (err, doc) => {
if (err) {
console.log(err);
}
if (doc) {
console.log(doc.name);
} else {
console.log('Empty');
}
});
The function you pass to then is called with the returned document (or null) if the operation succeeds, and the catch is called with the error if the operation fails (e.g. no connection). Putting it together looks like this:
User.findOne({_id: msg.chat.id})
.then(doc => {
if (doc) {
console.log(doc.name);
} else {
console.log('Empty');
}
}).catch(err => {
if (err) {
console.log(err);
}
});
As an aside, when you are searching for one document by id, then you can use findById:
User.findById(msg.chat.id)
.then(doc => {
if (doc) {
console.log(doc.name);
} else {
console.log('Empty');
}
}).catch(err => {
if (err) {
console.log(err);
}
});
Better switch to ES2017 async/await syntax, you can avoid Promise Hell
async function foo () {
try {
var doc = await User.findOne({_id: msg.chat.id}).exec()
if (doc)
return console.log(doc.name);
console.log('Empty');
} catch (err) { console.log(err) }
}
foo()
This will help you when you're going to nest DB calls or using for...loops.
async function foo () {
try {
var users = await User.find({}).exec()
for (var user in users) {
var tweets = await Tweet.find({_user: user._id}).exec()
user.tweets = tweets.map(t => t.text)
await user.save()
}
} catch (err) { console.log(err) }
}
foo()