NodeJS Promise then not executed - node.js

I need some help. It's my first try with promises.
Here is my code for the promise:
const deleteUniversRefInTarget = (universName, targetName) => {
console.log('Appel de deleteUniversRefInTarget')
const promis = new Promise((resolve, reject) => {
Target.findOneAndUpdate({ univers: universName, name: targetName },
(err, target) => {
console.log('Entrée dans la promesse')
if (err) {
reject(err)
} else {
if (target === null) {
reject(TypeError(`Invalid univers'n name ${universName}`))
} else {
if (target.univers.length === 1) {
resolve('deleteTarget')
} else {
target.univers.splice(target.univers.indexOf(universName), 1)
resolve('dereferencedUnivers')
}
}
}
})
})
return promis
}
I call this promise here :
exports.deleteATarget = (req, res) => {
deleteUniversRefInTarget(req.params.universName, req.params.targetName)
.then((response) => {
console.log('Fin du traitement de la promesse')
if (response === 'deleteTarget') {
Target.findOneAndDelete({ name: req.params.targetName, univers: req.params.universName },
(err, target) => {
if (err) {
res.send(err)
}
res.json({ message: `Target ${target.name} isn't used in any univers, so we deleted it` })
})
} else {
res.json({ message: `Target ${req.params.targetName} no longer used in ${req.params.universName} univers` })
}
})
.catch((error) => {
res.send(error)
})
}
In the console, I can see :
Appel de deleteUniversRefInTarget
But not Fin du traitement de la promesse
So ... do you know what I'm doing bad ?

I'm not sure I understood everything, but here is my new code about this anti-pattern :
```
const deleteTargetOrDerefUniversInTarget = (universName, targetName) => {
const promis = new Promise((resolve, reject) => {
Target.findOne({ name: targetName, univers: universName })
.then((target) => {
if (target === null) {
reject(TypeError(`Invalid univers'n name ${universName} or target's name ${targetName}`))
} else if (target.univers.length === 1) {
resolve({ action: 'deleteTarget', target })
} else {
resolve({ action: 'dereferencedUnivers', target })
}
})
.catch((err) => {
reject(err)
})
})
return promis
}
exports.deleteATarget = (req, res) => {
deleteTargetOrDerefUniversInTarget(req.params.universName, req.params.targetName)
.then((response) => {
if (response.action === 'deleteTarget') {
Target.findOneAndDelete({ name: response.target.name, univers: req.params.universName })
.then((target) => {
res.json({ message: `Target ${target.name} isn't used in any univers, so we deleted it` })
})
.catch((err) => {
res.status(err.status).json(err)
})
} else {
response.target.univers.splice(response.target.univers.indexOf(req.params.universName), 1)
response.target.save()
res.json({ message: `Target ${response.target.name} no longer used in ${req.params.universName} univers` })
}
})
.catch((error) => {
res.send(error)
})
}
```
In this new code, no more exec call.
The first promise just send back an action to perform that the caller manage.

Ok, sounds much better when I transform my mongoose query (findOneAndUpdate) to a promise :
`
const deleteUniversRefInTarget = (universName, targetName) => {
console.log('Appel de deleteUniversRefInTarget')
const promis = new Promise((resolve, reject) => {
Target.findOneAndUpdate({ univers: universName, name: targetName })
.exec()
.then((target) =>{
console.log('Entrée dans la promesse')
if (target === null) {
reject(TypeError(`Invalid univers'n name ${universName}`))
} else {
if (target.univers.length === 1) {
resolve('deleteTarget')
} else {
target.univers.splice(target.univers.indexOf(universName), 1)
resolve('dereferencedUnivers')
}
}
})
.catch((err) => {
reject(err)
})
})
return promis
}
`
And the difference is mainly the .exec() part.
I think we can say it's solve ... even if I'm not sure it's the correct way to do ot.

Related

FInding difficulty in updating a doc in MERN stack React Native

I don't know where II am missing something in the code as It's working clearly from postman.
my backend Nodejs server function is :
exports.updateFCMToken = (req, res) => {
try {
User.findByIdAndUpdate(
req.params.id,
{
$set: {
fcmToken: req.body.fcmToken
}
},
(err, doc) => {
if (err) {
console.log(err);
res.status(400).send('update FCMToken - Error')
}
return res.status(200).send('FCMToken Updated Successfully')
}
)
}
catch (err) {
console.log(err);
res.status(400).send('server Error - FCMToken')
}
}
From component I am calling the action:
useEffect(() => {
setTimeout(async () => {
dispatch(updateFCMTokenAction());
}, 1000);
}, [])
my action.js: (doc id and fcmtoken are not similar to output shown in code)
export const updateFCMTokenAction = () => {
return async (dispatch) => {
try {
dispatch({ type: userConstants.UPDATE_FCMTOKEN_REQUEST });
getToken();
const fcmToken = await AsyncStorage.getItem('fcmToken');
const user = await AsyncStorage.getItem('user');
const pushToken = {fcmToken};
const id = JSON.parse(user)._id; // output: 63806e0f4dzeb09a2c03f731
console.log('-----------------updateFCMTokenAction--------------');
console.log('updateFCMTokenAction-fcmToken:', pushToken); // output: {"fcmToken": "fv4-4GIWTymgrt7e3klaPs:APA91bGXOLTNfp4-j4dPVDEL-6lDVUA7GWZchwx4j2BlVPOvOsq3pDOk06xkfBE-Q-J6Q4zix8LX-Jf-69Ey2T22aYmbiVD4j4_kMbVlZa8ip1MRtQ-ZDs0hMpno53o7BjmB9Opc-LWR"}
const res = await axiosInstance.post(`/updatefcmtoken/${id}`, pushToken);
console.log('res: ', res);
dispatch({ type: userConstants.UPDATE_FCMTOKEN_SUCCESS, payload: res.data });
} catch (err) {
console.log('push-err: ', err)
dispatch({ type: userConstants.UPDATE_FCMTOKEN_FAILURE, payload: err });
}
}
}
I am getting an error as :
push-err: [AxiosError: Request failed with status code 400]
What am I missing/unable to see here ?
Thank You ,

My program writes the data to file successfully, but the URL data needs to be checked by my link checker. Node.js

https://github.com/strawberries73/OSD600-Journey-on-rocky-trails
I need the data converted to show URLs only for my Link Check to work. I have tried another solution but the new code solution deletes the conversion before it gets read. If there is a way to pull the URL's and get them to be written to a different file or the same file, my link checker would work.
// ExitCode
process.on("SIGTERM", () => {
server.close(() => {
console.log("Program is terminated");
});
});
//Flag labeling each URL as a good or bad
const _label = ({
good: "GOOD",
bad: "BAD"
});
//const getTelescope = fetch('http:/') data
async function getTelescopeData(){
//fetching data from local host
fetch("http://localhost:3000/posts").then(response => {
return response.json();
}).then(data => {
console.log(data);
//truncate the data and write to file
fs.truncate("telescopeData.txt", 0, function() {
for(i = 0; i < data.length; i++) {
fetch(`http://localhost:3000${data[i].url}`)
.then(res => {
return res.json();
}).then(telescopeData => {
//Append to telescopeData.txt
fs.appendFile("telescopeData.txt", telescopeData.html,
(err) => {
if(err) {
console.log(err)
.then.process(); //Termination
}
});
});
}
});
}
);
}
getTelescopeData(); //Data fetched
if(process.argv.length==2){
greetingMessage();
console.log("Hello");
}
else{
const filePath=path.join(__dirname,process.argv[2]);
fs.readFile(filePath,"utf-8",(err,data)=>{
if(err){
console.log("Fail to read file",err);
}
else{
const validUrl=data.match(/(http|https)(:\/\/)([\w+\-&#`~#$%^*.=/?:]+)/gi);
validUrl.forEach((url)=>{
fetch(url,{method:"HEAD",timeout:2000})
.then((res)=>{
if(res.status==200)
console.log(res.status,url.green,_label.good.rainbow);
else if(res.status==400||res.status==404)
console.log(res.status,url);
else console.log(res.status,url)
.then.process(); //Termination
})
.catch((error)=>{
console.log("404",url.red, _label.bad.bgRed);
});
});
}
});
}
Output of Data in the console
New Code tried, only it deletes the input after it has been written to file.
// ExitCode
process.on("SIGTERM", () => {
server.close(() => {
console.log("Program is terminated");
});
});
//Flag labeling each URL as a good or bad
const _label = ({
good: "GOOD",
bad: "BAD"
});
//const getTelescope = fetch('http:/') data
async function getTelescopeData() {
//fetching data from local host
fetch("http://localhost:3000/posts").then(response => {
return response.json();
}).then(data => {
console.log(data);
//truncate the data and write to file
fs.truncate("telescopeData.txt", 0, function () {
for (i = 0; i < data.length; i++) {
fetch(`http://localhost:3000${data[i].url}`)
.then(res => {
return res.json();
}).then(telescopeData => {
//Append to telescopeData.txt
fs.appendFile("telescopeData.txt", telescopeData.html,
(err) => {
if (err) {
console.log(err)
.then.process(); //Termination
}
});
});
}
});
// its not reading the file for some reason. File is empty when I add this.
fs.readFile("telescopeData.txt", "utf-8", (err, data) => {
if (err) {
console.log("Fail to read file", err);
}
else {
console.log(data);
console.log("^^^");
const validUrl = data.match(/(http|https)(:\/\/)([\w+\-&#`~#$%^*.=/?:]+)/gi);
console.log(validUrl);
console.log("^^^");
validUrl.forEach((url) => {
fetch(url, { method: "HEAD", timeout: 2000 })
.then((res) => {
if (res.status == 200)
console.log(res.status, url.green, _label.good.rainbow);
else if (res.status == 400 || res.status == 404)
console.log(res.status, url);
else console.log(res.status, url)
.then.process(); //Termination
})
.catch((error) => {
console.log("404", url.red, _label.bad.bgRed);
});
});
}
});
} // then ends
);
}
if (process.argv.length == 2) {
greetingMessage();
console.log("Hello");
} else if (process.argv[2] == "--telescope") {
console.log("Telescope");
getTelescopeData();
}
else {
const filePath = path.join(__dirname, process.argv[2]);
fs.readFile(filePath, "utf-8", (err, data) => {
if (err) {
console.log("Fail to read file", err);
}
else {
const validUrl = data.match(/(http|https)(:\/\/)([\w+\-&#`~#$%^*.=/?:]+)/gi);
validUrl.forEach((url) => {
fetch(url, { method: "HEAD", timeout: 2000 })
.then((res) => {
if (res.status == 200)
console.log(res.status, url.green, _label.good.rainbow);
else if (res.status == 400 || res.status == 404)
console.log(res.status, url);
else console.log(res.status, url)
.then.process(); //Termination
})
.catch((error) => {
console.log("404", url.red, _label.bad.bgRed);
});
});
}
});
}
async function getTelescopeData(body, url){
//fetching data from local host
const localRegex= /https?:\/\/localhost:[0-9]*/;
const baseurl=url.match(localRegex);
return JSON.parse(body).map((i)=>{return baseurl[0]+i.url;
})
}

how to find out where the error 500 , Node/ReactJs

I would like to explain my problem of the day.
I have an error 500 I cannot find where it comes from.
How can I fix this issue?
my fonction:
handleSubmit = (e) => {
e.preventDefault();
const userIdData = { id : e.target.id};
const config = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userIdData),
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
if (res.error) {
alert(res.error);
} else {
alert(`ajouté avec l'ID ${res}!`);
}
}).catch(e => {
console.error(e);
}).finally(() => this.setState({ redirect: true }));}
routes :
app.delete('/api/alluserpls', (req, res, ) => {
const userId = req.body.id;
const formData = req.body
connection.query('DELETE alluserpls WHERE id = ?',[formData, userId], err => {
if (err) {
res.status(500).send("Erreur lors de la modification des users");
} else {
res.sendStatus(200);
}
});
});
can you try this
app.delete('/api/alluserpls', (req, res, ) => {
const userId = req.body.id;
const formData = req.body
connection.query('DELETE * from alluserpls WHERE id = ?',[ userId], err => {
if (err) {
res.status(500).send("Erreur lors de la modification des users");
} else {
res.sendStatus(200);
}
});
});
as you only need to pass the id of the user to delete it
you have an issue in your database query. Your DELETE query is wrong. It should be
DELETE * from table_name where condition;
connection.query('DELETE * from alluserpls WHERE id = ?',[userId], err => {
if (err) {
res.status(500).send("Erreur lors de la modification des users");
} else {
res.sendStatus(200);
}
});

Adding req object to Kue job

Been hunting the internet trying to find an answer to why the following doesn't work.
I am trying to pass in the req object when I add the job so that I have access to it when the job is processed.
But the process is never executed when the whole req object is passed to job.data. Yet I can pass parts of the req object.
What I'm trying to do maybe anti-pattern and a big no no. But, I am trying to understand why it won't work. It seems strange that it just continues without any error.
Below is an example, hopefully it is clear.
My kue is abstracted into a separate file, and initialised onto app.locals.Q as follows:
// Q.js
class Q {
constructor(options) {
this.q = kue.createQueue(options)
}
addJob = (name, data) => {
return Queue.create({
queue_job: name,
queue_route: data.route,
queue_user: data.user,
queue_added: new Date(),
})
.then(response => {
this.q.create(name, {
id: response.get('queue_id'),
route: data.route,
request: data.request
})
.save();
return Promise.resolve(response);
})
.catch(error => {
return Promise.reject(error);
});
processJob = (name, work, options = {}) => {
const {concurrency} = options;
this.q.process(name, concurrency || 1, (job, done) => {
const {data: {id, route, request}} = job;
Queue.update({
queue_running: true
}, {
where: {
queue_id: id
}
})
.then(() => {
if (process.env.NODE_ENV !== 'production') {
console.log(`running job ${id} from ${route}`);
}
return new Promise((resolve, reject) => {
return work(resolve, reject, request);
});
})
.then(results => {
return Queue.update({
queue_running: false,
queue_completed: new Date(),
queue_results_path: results || null
}, {
where: {
queue_id: job.data.id
}
});
})
.then(() => {
if (process.env.NODE_ENV !== 'production') {
console.log(`completed job ${id} from ${route}`);
}
done();
})
.catch((error) => {
if (process.env.NODE_ENV !== 'production') {
console.log(`failed job ${id} from ${route}`);
console.log(error);
}
Queue.update({
queue_running: false,
queue_error: `${error}`
}, {
where: {
queue_id: id
}
})
.then(() => {
done(error);
})
.catch(err => {
console.error(err);
done(err);
});
});
});
};
};
// example route
queue = (req, res) => {
const {locals: {Q}} = req.app;
Q.addJob('foo', {
route: req.path,
user: req.user.get('username'),
request: req
})
.then(queue_id => {
Q.processJob('foo', (resolve, reject, request) => {
console.log(request)
resolve('complete')
})
res.json({sucess: true})
})
}
redis can't serialize the req object.
kue simply silently fails.

how to bypass multiple then in of mongoose

I Don't want to make checks as if (!isPresent) then do this ....
Is their any way to bypass all the then when my work is complete
var isPresent=false;
myPromise
.then((employee) => {
if (employee) {
// throw 'employee already exist';
isPresent = true;
return res.data(mapper.toFullModel(employee));
}
return model;
});
.then(model => {
if (!isPresent) {
return new db.employee(model).save();
}
})
.then(employee => {
if (!isPresent) {
employee.token = auth.getToken(employee);
return employee.save();
}
})
.then(employee => {
if (!isPresent) {
res.data(mapper.toFullModel(employee));
}
})
.catch(err => {
res.failure(err);
});
You can rewrite your promise chain so the second part of it gets nested:
myPromise.then(employee => {
if (employee) {
return res.data(mapper.toFullModel(employee));
}
return new db.employee(model).save().then(employee => {
employee.token = auth.getToken(employee);
return employee.save();
}).then(employee => {
return res.data(mapper.toFullModel(employee));
});
}).catch(err => {
res.failure(err);
});

Resources