I need to fix the error on code below, can someone help me please?. The code is written on JS(NodeJs). The error is this (...).then is not a function. Thanks.
try {
var decoded = jwt.decode(JWTToken, { complete: true });
var audience = decoded.payload.aud;
return db.checkAudience(audience).then(ehClient => {
if (ehClient == true) {
return db.getCreditsGeneral(sgecode, collections, year).then(total => {
let result = [];
total.forEach(item => {
result.push({
collection: item.Sistema,
levelType: item.idNivelEnsino,
grade: item.codPortal
});
});
return result;
});
} else {
return "not authorized";
}
});
} catch (err) {
return { erro: err.message };
}
Related
Is there a better way to orchestrate the below code in Rxjs ?
and from Javascript perspective Promise/Asyc/Await which will be better considering some hard error and soft error handlings.
Couple of calls are hard dependency which are marked as hard true in the error and on subsequent error handler checks and re throw it. and soft errors are added to final data.error for any processing based on the soft errors.
How this can be better done ?
const { Observable } = require('rxjs');
const { map, filter, flatMap, concatMap } = require('rxjs/operators');
function testcallback(fail, callback) {
if (fail == true) {
setTimeout(function(){ callback(new Error({ message: "Operation failed" })); }, 100);
}
else {
setTimeout(function(){ callback(null, 10); }, 100);
}
}
function createData(param) {
return Observable.bindNodeCallback(testcallback)(param);
}
function associateData(param) {
return Observable.bindNodeCallback(testcallback)(param);
}
function removeData(param) {
return Observable.bindNodeCallback(testcallback)(param);
}
function markAssociateSuccess(param) {
return Observable.bindNodeCallback(testcallback)(param);
}
function removeOldData(param) {
return Observable.bindNodeCallback(testcallback)(param);
}
function getAllData() {
return Observable.of( {error:null, data:[333]});
}
function updateData(updateData) {
let param = updateRequest.param;
return createData(1 == param)
.catch((err) => {
err.errorStep = 'CREATE_DATA';
err.hard = true;
throw (err);
}).flatMap(
() => {
return associateData(2 == param)
.catch((err) => {
err.errorStep = 'ASSOCIATE_DATA';
err.hard = true;
return removeData(3==param)
.map(() => {
throw (err);
});
});
},
(createDataResponse, associateDataResponse) => {
return [createDataResponse, associateDataResponse];
}
)
.flatMap(() => {
if (updateData.markAssociationSuccess) {
return markAssociateSuccess(4 == param);
} else {
return Observable.of({});
}
}).catch((err) => {
if (err.hard) {
throw (err);
}
err.errorStep = 'ASSOCIATE_SUCCESS';
return Observable.of({ error: err });
})
.flatMap((data) => {
if (data.error) {
return Observable.of(data);
}
return removeOldData(5 == param);
}).catch((err) => {
if (err.hard) {
throw (err);
}
err.errorStep = 'REMOVE_OLD_DATA';
return Observable.of({ error: err });
})
.flatMap(
function fetchData() {
return getAllData();
},
function resultSelector(prevRes, { error, data }) {
if (error) {
return {};
}
if (prevRes.error) {
data.error = prevRes.error;
}
return data;
}
)
.subscribe(
function onNext(data) {
console.log("Successful operation final data: " + data);
},
function onError(err) {
console.log("Errored out" + JSON.stringify(err));
},
function onComplete() {
console.log("Stream got completed");
}
);
}
const updateRequest = {
param:1,
markAssociationSuccess: true
}
updateData(updateRequest);
I did use sfDoc !== undefined, but still I'm getting the error of object is possibly undefined. Am I doing anything wrong here?
return database.runTransaction(function (transaction) {
return transaction.get(sfDocRef).then(sfDoc => {
if (!sfDoc.exists) {
throw "Document does not exist!";
}
if (sfDoc !== undefined) {
var usedCount = sfDoc.data().usedCount + 1;
transaction.update(sfDocRef, { usedCount: usedCount });
}
return transaction;
});
}).then(function () {
console.log("Tag field changed!");
return true;
}).catch(function (error) {
console.log("Error in changing Tag field: ", error);
return false;
});
Try this example. Check for the sfDoc and return transaction.update, So that then wait to resolve the promise. According to document, you don not has to check for sfDoc. It will be always defined.
return database
.runTransaction(function (transaction) {
return transaction.get(sfDocRef).then((sfDoc) => {
if (sfDoc && sfDoc.exists) {
var usedCount = sfDoc.data().usedCount + 1;
return transaction.update(sfDocRef, { usedCount: usedCount });
} else {
throw "Document does not exist!";
}
});
})
.then(function () {
console.log("Tag field changed!");
return true;
})
.catch(function (error) {
console.log("Error in changing Tag field: ", error);
return false;
});
i have a function called 'updateProfile()' which has a condition which is if(emailChangeConfirm), this condition depends upon the value of variable 'emailChangeConfirm' , this variable gets the value returned by another function called 'updateEmailAllProcessing()'
the condition 'if(emailChangeConfirm)' is not getting satisfied at all because compiler is not waiting for the function 'updateEmailAllProcessing()' to return the value for variable 'emailChangeConfirm'.
I used async/await for this but that is also not working as i want
Desired Solution :
function 'updateProfile()' must wait for the function 'updateEmailAllProcessing()' to get the result in 'emailChangeConfirm' so that i can enter in the condition 'if(emailChangeConfirm)'.
I am using typescript and working on hybrid app with ionic 3 and angular 5.
async updateProfile(updatedData : Credentials,tarUser : Credentials)
{
// console.log(tarUser,'<<--->>>',updatedData)
let count : number = undefined;
let emailChangeConfirm : boolean;
if(updatedData.name)
{
if(tarUser.name != updatedData.name)
tarUser.name = updatedData.name;
else
count++;
}
if(updatedData.email)
{
if(tarUser.email != updatedData.email)
{
**emailChangeConfirm = await this.updateEmailAllProcessing();**
console.log(emailChangeConfirm)
**if(emailChangeConfirm)
tarUser.email = updatedData.email;**
}
else
count++;
}
if(updatedData.phoneNo)
{
if(tarUser.phoneNo != updatedData.phoneNo)
tarUser.phoneNo = updatedData.phoneNo;
else
count++;
}
if(updatedData.photoURL)
{
if(tarUser.photoURL != updatedData.photoURL)
tarUser.photoURL = updatedData.photoURL;
else
count++;
}
if(count)
this.mesService.presentToast('Nothing Updated!!')
else **if(emailChangeConfirm)**
{
this.dbServe.editUser(tarUser).then(() =>
{
console.log("User Edited Successfully with email change too");
this.authServ.updateEmail(tarUser.email).then(() =>
{
console.log('login email updated');
this.authServ.logout();
})
//this.close();
})
}
else
{
this.dbServe.editUser(tarUser).then(() =>
{
console.log("User Edited Successfully with No email change");
this.close();
})
}
}
**async updateEmailAllProcessing()**
{
let result : boolean;
let alert = this.mesService.emailChangeConfirmation();
alert.present();
alert.onDidDismiss((data) => {
console.log('data->',data);
if(data)
{
let alert1 = this.mesService.passwordPrompt();
alert1.present();
alert1.onDidDismiss(data1 =>
{
console.log('password->',data1);
if(data1)
{
this.authServ.reauthenticateUser(data1).then(() =>
{
console.log('User Reauth Done');
result = true;
})
}
else
result = false;
})
}
else
result = false;
})
**return result;**
}
You need updateEmailAllProcessing to return a promise so you can await on it. and resolve the promise with the result inside the callback.
async updateEmailAllProcessing()
{
return new Promise((resolve, reject) => {
let result: boolean;
let alert = this.mesService.emailChangeConfirmation();
alert.present();
alert.onDidDismiss((data) => {
console.log('data->', data);
if (data) {
let alert1 = this.mesService.passwordPrompt();
alert1.present();
alert1.onDidDismiss(data1 => {
console.log('password->', data1);
if (data1) {
this.authServ.reauthenticateUser(data1).then(() => {
console.log('User Reauth Done');
resolve(true);
})
}
else
resolve(false);
})
}
else
resolve(false);
})
});
}
User.find({ refUser: req.params.userName }).then(function (users) {
var network_users = [];
network_users.push(users);
users.forEach(function (u) {
network_users.push(User.find({ refUser: u.toObject().userName }));
})
return Promise.all(network_users);
I have 4 users, I expected receive a json with all of childrens but I only received the first and the children of this first.
Someone can help me with this loop? Please! Thanks so much!!!!
function asyncLoop(iterations, func, callback, foo) {
var done = false;
var loop = {
next: function () {
if (done) {
return;
}
if (iterations) {
func(loop);
} else {
done = true;
if (callback) callback(foo);
}
},
isEnd: function () {
return done;
},
refresh: function (it) {
iterations = it;
},
break: function () {
done = true;
callback();
}
};
loop.next();
return loop;
}
function bfs(userName, callback) {
userName = String(userName);
var q = [], res = [];
User.findOne({ "refUser" : userName }).lean().exec(function (err, root) {
root.depth = 0;
q.push(root);
asyncLoop(q.length, function (loop) {
res.push(q[0]);
User.find({ "refUser" : q[0].userName }).lean().exec(function (err, new_nodes) {
if (err) console.log(err);
else {
var d = q[0].depth;
q.shift();
loop.refresh(new_nodes.length + q.length);
if (new_nodes.length > 0) {
new_nodes.forEach(function (new_node) {
new_node.depth = d + 1;
q.push(new_node);
});
}
loop.next();
}
});
}, function () { callback(res) });
});
}
Finishing:
bfs(req.params.userName,function(callback){
res.send(callback)
})
I have two js files. i am able to get data from mongodb by calliing bookDao.getActiveBookByCategoryId().
My Problem
In categoryDao.js file i am trying to update resultJson.book_countinside BookDao.getActiveBookByCategoryId() method. but it is not updating. So may i know how to fix this.
here book_count property in resultJson is still 0.
categoryDao.js
module.exports.getAllActiveCategory = (callback) => {
Category.find({
is_delete : false
}, (error, result) => {
if(error) {
console.log(error);
callback(commonUtil.ERROR);
}
if(result) {
var categoryArray = [];
for(var i=0; i<result.length; i++) {
var categorySingle = result[i];
var resultJson = {
_id : categorySingle._id,
category_name : categorySingle.category_name,
created_on : categorySingle.created_on,
book_count : 0
}
BookDao.getActiveBookByCategoryId(categorySingle._id, (bookResult) => {
if(bookResult) {
if(bookResult.length > 0) {
resultJson.book_count = bookResult.length;
}
}
});
categoryArray.push(resultJson);
}
callback(categoryArray);
}
});
}
bookDao.js
module.exports.getActiveBookByCategoryId = (categoryId, callback) => {
Book.find({
is_delete : false,
category : categoryId
}, (error, result) => {
if(error) {
console.log(error);
callback(commonUtil.ERROR);
}
if(result) {
callback(result);
}
});
}
Try this, In your code categoryArray.push(resultJson); will not wait for BookDao.getActiveBookByCategoryId to finish because of async behavior.
module.exports.getActiveBookByCategoryId = (categoryId) => {
return Book.count({
is_delete: false,
category: categoryId
});
}
module.exports.getAllActiveCategory = async () => {
try {
// Find all category
const result = await Category.find({
is_delete: false
});
// Create array of promise
const promises = result.map(categorySingle => BookDao.getActiveBookByCategoryId(categorySingle._id));
// Get array of Category count
const data = await Promise.all(promises);
// update count in result
return result.map((categorySingle, i) => {
categorySingle.book_count = data[i];
return categorySingle;
});
} catch (error) {
console.log(error);
}
}