How to Make These Functions Run in Order - javascript

I have the following functions. The problem I'm having is that the updateInterviewArrays() has a loop in it to fetch and store data, which works. But I need the updateStates and doScoreMath functions called after it to wait, and go in order after it's finished. I can't seem to make that happen though.
componentDidMount() {
this.getScoresFromTables();
}
getScoresFromTables() {
fetch(API_URL + `/interviews/${this.props.auditId}`)
.then((res) => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((result) => {
this.setState({completedInterviews: result}, () => this.updateInterviewArrays());
})
.catch((error) => {
console.log(error);
})
.then(this.updateStates())
.catch((error) => {
console.log(error);
})
.then(this.doScoreMath());
}
updateInterviewArrays() {
const totalInterviews = this.state.completedInterviews.length;
const tableSections = [
'audit_general',
'audit_culture',
'audit_performance',
'audit_policies',
'audit_risk',
'audit_strategy',
'audit_rewards',
'audit_workforce'
];
for (let i = 0; i < totalInterviews; i++){
for (let j = 0; j < 8; j++){
this.grabTableData(tableSections[i], this.state.completedInterviews[j].employee_id);
}
}
}
async grabTableData (tableName, employeeId) {
await fetch(API_URL + `/responses/${tableName}/${employeeId}`)
.then((res) => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((result) => {
if (tableName === "audit_general") {
tableData.audit_general.push(result[0]);
} else if (tableName === "audit_culture") {
tableData.audit_culture.push(result[0]);
} else if (tableName === "audit_performance") {
tableData.audit_performance.push(result[0]);
} else if (tableName === "audit_policies") {
tableData.audit_policies.push(result[0]);
} else if (tableName === "audit_risk") {
tableData.audit_risk.push(result[0]);
} else if (tableName === "audit_strategy") {
tableData.audit_strategy.push(result[0])
} else if (tableName === "audit_rewards") {
tableData.audit_rewards.push(result[0]);
} else if (tableName === "audit_workforce") {
tableData.audit_workforce.push(result[0]);
}
console.log(result);
console.log(tableData);
})
.catch((error) => {
console.log(error);
})
// .then(() => this.updateStates())
// .catch((error) => {
// console.log(error);
// })
// .then(() => this.doScoreMath())
;
}

Related

Array is empty after api call using vuejs3

I'm using vue-js and i encountered this problem where i call a get all api and then store it in an array. The logic works perfectly fine in the first component, however when i copied literally the exact same code and pasted it in a second component the call for some reason returns an empty array instead of the array of users. Here is the component
import UsersInServiceCenterService from "../services/UsersInServiceCenterService";
import UserService from "../services/UserService";
export default {
name: "service center",
data() {
return {
currentServiceCenter: null,
message: '',
listOfSpecificServiceCenter1: [],
listOfSpecifiedUsers1: [],
id:"",
};
},
methods: {
getServiceCenter(id) {
ServiceCenterService.get(id)
.then((response) => {
this.currentServiceCenter = response.data;
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
},
updateServiceCenter() {
ServiceCenterService.update(this.currentServiceCenter.id, this.currentServiceCenter)
.then((response) => {
console.log(response.data);
this.message = "The service center was updated successfully!";
})
.catch((e) => {
console.log(e);
});
},
deleteServiceCenter() {
ServiceCenterService.delete(this.currentServiceCenter.id)
.then((response) => {
console.log(response.data);
this.$router.push({ name: "service centers" });
})
.catch((e) => {
console.log(e);
});
},
retrieveAllUsersByServiceCenterId(currentServiceCenter){
UsersInServiceCenterService.getAllUsersByServiceCenterId(currentServiceCenter.id)
.then((response) => {
this.listOfSpecificServiceCenter1 = response.data;
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
},
retrieve(){
this.retrieveAllUsersByServiceCenterId(this.currentServiceCenter);
if(this.listOfSpecificServiceCenter1.length!=0){
for(var i =0 ; i<this.listOfSpecificServiceCenter1.length;i++){
UserService.get(this.listOfSpecificServiceCenter1[i].userId)
.then((response) => {
this.listOfSpecifiedUsers1.push(response.data);
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
}
}
this.isEmpty = !this.isEmpty;
},
},
mounted() {
this.message = "";
this.getServiceCenter(this.$route.params.id);
},
};
</script>
getServiceCenter(id) works fine and it returns the service center. However both of the retrieve() and the retrieveAllUsersByServiceCenterId(currentServiceCenter) do not work at all and they return the empty array. Here is the first component which works totally fine with literally the exact same functions.
import UserService from "../services/UserService";
import UsersInServiceCenterService from "../services/UsersInServiceCenterService";
export default {
name: "servicecenters-list",
data() {
return {
serviceCenters: [],
users:[],
currentServiceCenter: null,
currentUser: null,
currentIndex: -1,
currentUserIndex: -1,
id: "",
searchValue: "",
isEmpty: false,
rows: [],
listOfSpecificServiceCenter:[],
listOfSpecifiedUsers:[],
};
},
methods: {
retrieveServiceCenters() {
ServiceCenterService.getAllServiceCenters()
.then((response) => {
this.serviceCenters = response.data;
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
},
retrieveUsers() {
UserService.getAllUsers()
.then((response) => {
this.users = response.data;
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
},
refreshList() {
this.retrieveServiceCenters();
//this.retrieveUsers();
this.currentServiceCenter = null;
this.currentIndex = -1;
//this.currentUser = null;
//this.currentUserIndex = -1;
},
setActiveServiceCenter(servicecenter, index) {
this.currentServiceCenter = servicecenter;
this.currentIndex = index;
},
setActiveUser(user,userIndex){
this.currentUser= user;
this.currentUserIndex = userIndex;
},
// showList(currentServiceCenter){
// for(var i =0;i<currentServiceCenter.users.length;i++){
// }
// },
retrieve(){
this.retrieveAllUsersByServiceCenterId(this.currentServiceCenter);
if(this.listOfSpecificServiceCenter.length!=0){
for(var i =0 ; i<this.listOfSpecificServiceCenter.length;i++){
UserService.get(this.listOfSpecificServiceCenter[i].userId)
.then((response) => {
this.listOfSpecifiedUsers.push(response.data);
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
}
}
this.isEmpty = !this.isEmpty;
},
retrieveAllUsersByServiceCenterId(currentServiceCenter){
UsersInServiceCenterService.getAllUsersByServiceCenterId(currentServiceCenter.id)
.then((response) => {
this.listOfSpecificServiceCenter = response.data;
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
},
addUserToServiceCenter(currentServiceCenter, currentUser) {
var data = {
serviceCenterId: parseInt(this.currentServiceCenter.id),
userId: parseInt(this.currentUser.id),
};
UsersInServiceCenterService.add(data)
.then((response) => {
//this.currentServiceCenter.id = response.data.id; //take care here
console.log(response.data);
this.submitted = true;
})
.catch((e) => {
console.log(e);
});
this.show=false
if(currentServiceCenter.users == Array.isArray(currentServiceCenter.users))
//currentServiceCenter.users = Array.isArray(currentServiceCenters.users) : [...currentServiceCenter.users, currentUser] : [currentUser]
currentServiceCenter.users.push(currentUser);
else{
currentServiceCenter.users = []
currentServiceCenter.users.push(currentUser);
}
},
removeAllServiceCenters() {
ServiceCenterService.deleteAllServiceCenters()
.then((response) => {
console.log(response.data);
this.refreshList();
})
.catch((e) => {
console.log(e);
});
},
searchId(id) {
ServiceCenterService.get(id)
.then((response) => {
this.currentServiceCenter = response.data;
})
.catch((e) => {
console.log(e);
});
this.refreshList();
// if(typeof id ==='string'){
// }
// else if(typeof id==='number'){
// CompanyService.get(id).then(response =>{
// this.currentCompany=response.data
// })
// .catch(e=>{
// console.log(e);
// });
// }
},
},
mounted() {
this.retrieveServiceCenters();
this.retrieveUsers();
},
computed:{
usersFilteredListByName(){
if(this.searchValue.trim().length >0){
return this.serviceCenters.filter((servicecenter) =>servicecenter.name.toLowerCase().includes(this.searchValue.trim()))
}
// if(this.searchValue.length>0 && isNaN(parseInt(this.searchValue))){
// return this.companies.filter((company) =>company.id.includes(this.searchValue))
// }
return this.serviceCenters
},
usersFilteredListById(){
if(this.searchValue.trim().length >0){
return this.serviceCenters.filter((servicecenter) =>servicecenter.id.toString().includes(this.searchValue))
}
return this.serviceCenters
},
}
};
</script>
You can ignore the rest of the functions and focus on the retrieve() and retrieveAllUsersByServiceCenterId(). Any help would be highly appreciated.

async and await not workingg

its not waiting for validation and just run the else part :| where is my mistake?
async validateBeforeSubmit(event) {
await this.$validator.validateAll().then( result => {
if (result) {
console.log(result); // just log the -> true
// go submit
}else{
console.log(result); // just log the -> false
event.preventDefault();
var elmnt = document.getElementById("drop_zone");
elmnt.scrollIntoView();
}
})
.catch(error=>console.log(error));
},
i'm using veevalidator and i define some custom rules that need afew seconds to resolve:
created() {
this.$validator.extend('unique', {
// getMessage: field => 'At least one ' + field + ' needs to be checked.',
async validate(value, arg) {
arg = arg[0];
let sw = false;
if (arg == 'n_code') {
let data = {
'n_code': value
}
await Axios.post(duplicate_ncode, data, {
headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') }
})
.then((response) => {
if (response.data == true) {
sw = true;
}
})
.catch(error => console.log(error));
if (sw) {
return true;
} else {
return false;
}
}
if (arg == 'email') {
let data = {
'email': value
}
await Axios.post(duplicate_email, data, {
headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') }
})
.then((response) => {
if (response.data == true) {
sw = true;
}
})
.catch(error => console.log(error));
if (sw) {
return true;
} else {
return false;
}
}
if (arg == 'mobile') {
let data = {
'mobile': value
}
await Axios.post(duplicate_mobile, data, {
headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') }
})
.then((response) => {
if (response.data == true) {
sw = true;
}
})
.catch(error => console.log(error));
if (sw) {
return true;
} else {
return false;
}
}
// console.log('questions', value, testProp, options.some((option) => option[testProp]));
// return true;
}
});
}
when user fill all fields it will check 3 api and that need momnets to check.
and i need to await to get the answer but there is somthing wrong which is not working.
please help
I believe what you want to do is:
async validateBeforeSubmit(event) {
try {
const result = await this.$validator.validateAll();
if (result) {
// go submit
} else {
event.preventDefault();
var elmnt = document.getElementById('drop_zone');
elmnt.scrollIntoView();
}
}
catch (e) {
console.log(e);
}
},

Using while loop in Promise()

I have a user list and i am checking all user with certain details.I am using sequelize js with express.I want to know that can we use while loop like this for searching and saving data in database.Please help me.Thanks In advance.
let royalty_bonus = async (sponsor) => {
return await new Promise((resolve, reject) => {
models.RoyaltyUser.findById(sponsor)
.then(async (sponsorRow) => {
let user_level = 1;
let sponsor_id = sponsorRow;
try {
while (sponsor_id != null && user_level <= 3) {
let level_length = await getLevel(sponsor_id.id, user_level);
if (user_level === 1 && level_length.length === 3) {
console.log('Level One Achieved By ', sponsor_id.id);
} else if (user_level === 2 && level_length.length === 9) {
console.log('Level Two Is Achieved By ', sponsor_id.id);
} else {
console.log('No Level');
}
await models.RoyaltyUser.findOne({where: {id: sponsor_id.sId}})
.then((sponsor_new_row) => {
sponsor_id = sponsor_new_row;
})
.catch((e) => {
console.log(' Inner Catch Error ', e.message);
reject();
});
user_level++;
}
resolve();
}
catch (e) {
reject(e);
}
})
.catch((e) => {
reject('catch ', e.message);
});
});
};
router.get('/royalty_user', async (req, res, next) => {
royalty_bonus(4)
.then(() => {
console.log('done');
})
.catch((e) => {
console.log('Catch two', e.message);
})
});
Avoid the Promise constructor antipattern, avoid return await, and don't mix .then callbacks with async/await syntax. You can simplify a lot:
async function royalty_bonus(sponsor) {
const sponsorRow = await models.RoyaltyUser.findById(sponsor);
let user_level = 1;
let sponsor_id = sponsorRow;
while (sponsor_id != null && user_level <= 3) {
let level_length = await getLevel(sponsor_id.id, user_level);
if (user_level === 1 && level_length.length === 3) {
console.log('Level One Achieved By ', sponsor_id.id);
} else if (user_level === 2 && level_length.length === 9) {
console.log('Level Two Is Achieved By ', sponsor_id.id);
} else {
console.log('No Level');
}
const sponsor_new_row = await models.RoyaltyUser.findOne({where: {id: sponsor_id.sId}});
sponsor_id = sponsor_new_row;
user_level++;
}
}
router.get('/royalty_user', (req, res, next) => {
royalty_bonus(4).then(() => {
console.log('done');
}, e => {
console.log('Catch two', e.message);
});
});

Chrome Dev tools - javascript snippet test : "Uncaught Syntax Unexpected End-of-input" error on last line

I am trying to test the following snippet using the Chrome Dev Tool, but I get this error on the last line of the snippet ... cannot find where it's wrong ...
function myPromise1(time1, ok1){
return new Promise((resolve, reject) => {
// do stuff 1 async
setTimeout(() => {
if ( ok1 ) {
resolve('stuff-1 worked')
} else {
reject(Error('stuff-1 failed'))
}
}, time1)
});
function myPromise2(time2, ok2){
return new Promise((resolve, reject) => {
// do stuff 2 async
setTimeout(() => {
if ( ok2 ) {
resolve('stuff-2 worked')
} else {
reject(Error('stuff-2 failed'))
}
}, time2)
});
function myPromise3(time3, ok3){
return new Promise((resolve, reject) => {
// do stuff 3 async
setTimeout(() => {
if ( ok3 ) {
resolve('stuff-3 worked')
} else {
reject(Error('stuff-3 failed'))
}
}, time3)
});
const c1 = '';
const c2 = '';
const c3 = '';
const promise1 = (val11, val12) => myPromise1(val11, val12)
.then(p1Result => {
c1 = p1Result;
return;
}, function(err1) {
console.log('Error: ', err1);
return;
});
const promise2 = (val21, val22) => myPromise2(val21, val22)
.then((p2Result) => {
c2 = p2Result;
return;
}, function(err2) {
console.log('Error: ', err2);
return;
});
const promise3 = (val31, val32) => myPromise2(val31, val32)
.then((p3Result) => {
c3 = p3Result;
return;
}, function(err3) {
console.log('Error: ', err3);
return;
});
const conditionalPromiseFlow = (...fns) => {
if(fns.length === 0) return Promise.resolve()
const [next] = fns;
return next()
.then(result => {
if(result) {
return conditional(...fns.slice(1));
}
return result;
})
}
conditionalPromiseFlow(() => promise1(1000, true), () => promise2(2000, true), () => promise3(3000, true))
.then(() => {
console.log('Status 200 - ALL DONE');
return;
})
.catch((error) => {
console.log('Status ', error.status, ' - ', error.message);
return;
}) <== Error stated here
this is the corrected snippets to test promises flow...
I can play with the main() line
conditionalPromiseFlow(() => promise1(1000, true), () => promise2(2000, true), () => promise3(3000, true))
the flow stops when one promise is rejected
function myPromise1(time1, ok1){
console.log('Promise1', time1, ok1);
return new Promise((resolve, reject) => {
setTimeout(() => {
if ( ok1 ) {
resolve('stuff-1 worked');
} else {
reject(Error('stuff-1 failed'));
}
}, time1);
});
}
function myPromise2(time2, ok2){
console.log('Promise2', time2, ok2);
return new Promise((resolve, reject) => {
setTimeout(() => {
if ( ok2 ) {
resolve('stuff-2 worked');
} else {
reject(Error('stuff-2 failed'));
}
}, time2);
});
}
function myPromise3(time3, ok3){
console.log('Promise3', time3, ok3);
return new Promise((resolve, reject) => {
setTimeout(() => {
if ( ok3 ) {
resolve('stuff-3 worked');
} else {
reject(Error('stuff-3 failed'));
}
}, time3);
});
}
let c1 = '';
let c2 = '';
let c3 = '';
const promise1 = (val11, val12) => myPromise1(val11, val12)
.then(p1Result => {
c1 = p1Result;
return;
}, function(err1) {
err1.status = 300;
throw err1;
});
const promise2 = (val21, val22) => myPromise2(val21, val22)
.then((p2Result) => {
c2 = p2Result;
return;
}, function(err2) {
err2.status = 300;
throw err2;
});
const promise3 = (val31, val32) => myPromise3(val31, val32)
.then((p3Result) => {
c3 = p3Result;
return;
}, function(err3) {
err3.status = 300;
throw err3;
});
const conditionalPromiseFlow = (...fns) => {
if(fns.length === 0) return Promise.resolve();
const [next] = fns;
return next()
.then(result => {
if(!result) {
return conditionalPromiseFlow(...fns.slice(1));
}
return result;
});
};
conditionalPromiseFlow(() => promise1(1000, true), () => promise2(2000, true), () => promise3(3000, true))
.then(() => {
console.log('Status 200 - ALL DONE');
return;
})
.catch((error) => {
console.log('Status ', error.status, ' - ', error.message);
return;
});

Javascript 'Promise' how to make Synchronous

I am using Ionic2/Typescript.
I have 2 Promise's that I want to have complete, before I continue (i.e synchronous). So I put the call to the 2 functions in a Promise.all(...), expecting them to complete before resolve is called.
I have the following code:
public openDatabase(): Promise<Array<Message>> {
let promise: Promise<Array<Message>> = new Promise<Array<Message>>(resolve => {
if (false && this.database && this.database != null) {
Promise.all([this.refreshChats(this.database), this.refreshMessages(this.database)]).then(() => {
console.log('openDatabase1: resolve');
resolve(this.messages);
});
} else {
this.database = new SQLite();
this.database.openDatabase({
name: "data.db",
location: "default"
}).then(() => {
Promise.all([this.refreshChats(this.database), this.refreshMessages(this.database)]).then(() => {
console.log('openDatabase2: resolve');
resolve(this.messages);
});
}, (error) => {
console.log("OPEN ERROR: ", error);
});
}
});
return promise;
}
public refreshChats(db: any): Promise<any> {
console.log('refreshChats ');
return db.executeSql("SELECT * FROM chats", [])
.then((chatData) => {
let promises: Array<any> = [];
this.chats = [];
if (chatData.rows.length > 0) {
for (var i = 0; i < chatData.rows.length; i++) {
promises.push(this.populateChat(db, chatData.rows.item(i)));
}
}
Promise.all(promises).then(() => {
console.log('refreshChats return this.chats.length = ' + this.chats.length);
return this.chats;
});
})
.catch(error => {
console.log("ERROR REFRESHING CHATS: " + JSON.stringify(error));
console.log(error);
});
}
From my console output, you can see that resolve is called before the chats are finished refreshing:
refreshChats
populateChat Object {...}
openDatabase2: resolve
refreshChats return this.chats.length = 1
Any advise on how I should structure my Promises is appreciated.
You need to return new promises from inner promise callbacks:
public openDatabase(): Promise<Array<Message>> {
let promise: Promise<Array<Message>> = new Promise<Array<Message>>(resolve => {
if (false && this.database && this.database != null) {
return Promise.all([this.refreshChats(this.database), this.refreshMessages(this.database)]).then(() => {
console.log('openDatabase1: resolve');
resolve(this.messages);
});
} else {
this.database = new SQLite();
return this.database.openDatabase({
name: "data.db",
location: "default"
}).then(() => {
return Promise.all([this.refreshChats(this.database), this.refreshMessages(this.database)]).then(() => {
console.log('openDatabase2: resolve');
resolve(this.messages);
});
}, (error) => {
console.log("OPEN ERROR: ", error);
});
}
});
return promise;
}
public refreshChats(db: any): Promise<any> {
console.log('refreshChats ');
return db.executeSql("SELECT * FROM chats", [])
.then((chatData) => {
let promises: Array<any> = [];
this.chats = [];
if (chatData.rows.length > 0) {
for (var i = 0; i < chatData.rows.length; i++) {
promises.push(this.populateChat(db, chatData.rows.item(i)));
}
}
return Promise.all(promises).then(() => {
console.log('refreshChats return this.chats.length = ' + this.chats.length);
return this.chats;
});
})
.catch(error => {
console.log("ERROR REFRESHING CHATS: " + JSON.stringify(error));
console.log(error);
});
}
Note, return Promise.all and return this.database.openDatabase.

Categories

Resources