this is the first function , i have this function getAffliateCodesAsync() my requirement is to call this method from inside other function (function -2 >> generateCriBodyWithCreParameter(..))
and pass the returning value of >>(function-1) getAffliateCodesAsync(), into the third function and use that value in (function -3) checkLessorMagnitudeCode(..) and use the returning value of function-2 in function-3 at place where codeList is used, Please help
//function-1.
async function getAffliateCodesAsync(){
console.debug("==AFFILIATE_CODES==");
const ApplicationParameter = loopback.getModel('ApplicationParameter');
const applicationParamFieldValue = await ApplicationParameter.find({
where: {
fieldName: 'AFFILIATE_CODES'
},
fields: ['fieldValue']
});
return (applicationParamFieldValue.length)? applicationParamFieldValue.map(entity => String(entity['fieldValue'])):[];
}
//2.function-2
const generateCriBodyWithCreParameter = (positions, lotNumber, cutOffDate) => {
const CreParameter = loopback.getModel('CreParameter');
let creId = 1;
const positionData = [];
const content = [];
return CreParameter.find()
.then((creParameterList) => {
const promises = positions.map((position) => {
const cutOffDatePreviousMonth = getCutOffDatePreviousMonth(position.accountingDate);
return positionNativeProvider.getPositionInformationForPreviousCutOffDateForCriApf(
position, cutOffDatePreviousMonth)
.then((positionRetrieved) => {
const positionLowerCase = _.mapKeys(position, (value, key) => _.toLower(key));
const creParameters = _.filter(creParameterList, {
flowType: 'MI',
event: 'POSITION',
liabilityAmortizationMethod: position.liabilityAmortizationMethod
});
for (const creParameter of creParameters) {
const atollAmountValue = getAtollAmountValue(positionLowerCase, creParameter);
if (atollAmountValue && matchSigns(atollAmountValue, creParameter.amountSign)) {
const lineGenerated = checkContractLegalStatusForCri(position, creParameter,
atollAmountValue, content, creId, lotNumber, cutOffDate, positionRetrieved);
//No Line is generated in this case so the creId must not incremente
if (lineGenerated !== -1) {
positionData.push({
positionId: position.id,
creId
});
creId++;
}
}
}
});
});
return Promise.all(promises)
.then(() => {
return {
contentCreBody: content.join('\n'),
positionData
};
});
});
};
//function -3
const checkLessorMagnitudeCode = (lessorMagnitudeCode,codeList=[]) => {
if (!lessorMagnitudeCode) return false;
if (_.size(lessorMagnitudeCode) === 5 &&
(_.startsWith(lessorMagnitudeCode, 'S') || _.startsWith(lessorMagnitudeCode, 'T'))
&& codeList.includes(lessorMagnitudeCode)) {
return true;
}
return false;
};
//above codelist where I want to use the returning value
Related
I have the following React code,
const useDynamicReplaceVariable = ({ label, formikValues, fieldsTypes }) => {
const { locale } = useTranslationState();
const formattedLabel = useMemo(() => {
const variablesRegex = /\?([\w-]+)\?/g;
let labelResult = label;
if (variablesRegex.test(label)) {
labelResult = ' ';
if (Object.keys(formikValues).length > 0) {
labelResult = label.replace(variablesRegex, (_, ...[variable]) => {
const type = fieldsTypes[variable];
// Set undefined or null to empty
let variableValue = (formikValues[variable] === undefined || formikValues[variable] == null) ? '' : formikValues[variable];
if (variableValue && [DesignerDdTypes.DatePicker, DesignerDdTypes.DatetimePicker].includes(type)) {
variableValue = dateToString(variableValue, locale, type === DesignerDdTypes.DatetimePicker);
}
return variableValue;
});
}
}
return labelResult;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [label, JSON.stringify(formikValues)]);
return { formattedLabel };
};
I can't understand the line labelResult = label.replace(variablesRegex, (_, ...[variable]), when no variable is defined, how come spread syntax is applied over it?
...[variable] is a shorthand for
function someFunction(...args) {
const [variable] = args
}
someFunction(1, 2, 3, 4, 5)
function someFunction(arg1, ...args) {
console.log('arg1', arg1)
console.log('args', args)
const [variable] = args
console.log('variable', variable)
}
someFunction(1, 2, 3, 4, 5)
function someFunction(arg1, ...[variable]) {
console.log('arg1', arg1)
console.log('variable', variable)
}
This question already has answers here:
JavaScript array .reduce with async/await
(11 answers)
Closed 6 months ago.
I need to fetch values from another API using the guid inside this particular array, then group them together (hence I used reduce Javascript in this case)
However, I could not get those values sumEstimatedHours and sumWorkedHours as expected. Can someone suggest a method please?
export const groupProjectsByPM = (listOfProjects) => {
const dir = "./json";
const estimatedHours = fs.existsSync(dir)
? JSON.parse(fs.readFileSync("./json/phases.json", "utf-8"))
: null;
let sumWorkedHours, sumEstimatedHours;
const groupedProjects = listOfProjects?.reduce(
(
group,
{
guid,
projectOwner: { name: POName },
name,
customer: { name: customerName },
deadline,
calculatedCompletionPercentage,
}
) => {
listOfProjects.map(async (element, index) => {
// const element = listOfProjects[index];
sumWorkedHours = await getWorkhoursByProject(element?.guid).then(
(res) => {
return res.reduce((acc, cur) => {
return acc + cur.quantity;
}, 0);
}
);
const filteredEstimatedHours = estimatedHours.filter(
(item) => item.project.guid === element.guid
);
sumEstimatedHours = filteredEstimatedHours.reduce((acc, cur) => {
return acc + cur.workHoursEstimate;
}, 0);
group[POName] = group[POName] || [];
group[POName].push({
guid,
name,
POName,
customerName,
deadline,
calculatedCompletionPercentage,
sumEstimatedHours,
sumWorkedHours,
});
return group;
});
return group;
},
[]
);
return groupedProjects;
};
here is an example of async/await inside reduce:
let's assume that we have an array of numbers
const arrayOfNumbers = [2,4,5,7,6,1];
We are going to sum them using reduce function:
const sumReducer = async () => {
const sum = await arrayOfNumbers.reduce(async (promisedSum, num) => {
const sumAcc = await promisedSum
// any promised function can be called here..
return sumAcc + num
}, 0)
console.log(sum)
}
So the trick is to remember to await the accumulator inside the reduce function
export const groupProjectsByPM = async (listOfProjects) => {
const dir = "./json";
const estimatedHours = fs.existsSync(dir)
? JSON.parse(fs.readFileSync("./json/phases.json", "utf-8"))
: null;
let sumWorkedHours, sumEstimatedHours;
const groupedProjects = await listOfProjects?.reduce(
async (
promisedGroup,
{
guid,
projectOwner: { name: POName },
name,
customer: { name: customerName },
deadline,
calculatedCompletionPercentage,
}
) => {
listOfProjects.map(async (element, index) => {
//accumulator in your case is group
const group = await promisedGroup;
// const element = listOfProjects[index];
sumWorkedHours = await getWorkhoursByProject(element?.guid).then(
(res) => {
return res.reduce((acc, cur) => {
return acc + cur.quantity;
}, 0);
}
);
const filteredEstimatedHours = estimatedHours.filter(
(item) => item.project.guid === element.guid
);
sumEstimatedHours = filteredEstimatedHours.reduce((acc, cur) => {
return acc + cur.workHoursEstimate;
}, 0);
group[POName] = group[POName] || [];
group[POName].push({
guid,
name,
POName,
customerName,
deadline,
calculatedCompletionPercentage,
sumEstimatedHours,
sumWorkedHours,
});
return group;
});
return group;
},
[]
);
return groupedProjects;
};
Best of luck ...
I have a 2 function,
inside my runConfigComplianceDeviceOnClick I am calling the getDeviceRunningCompliance function to get some other data and based on both the results I have to return an object,
But What I am observing my data from the getDeviceRunningCompliance (Axios request to get data) function is not returned and it executes next lines,
but when I see in the console value is updated,
How to handle this case,
how to wait for the function to execute and then go next javascript? wanted to deal with asynchronous data then proceed further to the next lines...
/**
* #param {*} graphTable
*/
const runConfigComplianceDeviceOnClick = graphTable => {
let selectedDevices = graphTable.dTable.store.state.selectedRowsData;
let paramSelectedDevices;
let filteredSelectedDevices;
let finalParam;
let supportedDevices = true;
let some = getDeviceRunningCompliance(selectedDevices);
console.log("getDeviceRunningCompliance some ", some)
if (some.length) {
filteredSelectedDevices = selectedDevices.map(function(device, index) {
console.log("getDeviceRunningCompliance some filteredSelectedDevices", some)
if (notSupportedFamilies.includes(device.series)) {
// console.log(i18n.no_support_available_for_aireos);
supportedDevices = false;
} else {
// console.log(i18n.label_configuration_data_not_available);
supportedDevices = true;
}
let valsss = some.find(x => x.id === device.id);
console.log("valsss ", valsss)
return {
id: device.id,
hostname: device.hostname,
val: device.complianceStoreStatus.complianceStatus,
collectionStatus: device.collectionStatus,
series: device.series,
supportedDevices: supportedDevices
};
});
finalParam = filteredSelectedDevices.filter(function(val, index) {
return val.supportedDevices && val.val === "NON_COMPLIANT"; // this should be enable
});
paramSelectedDevices = JSON.stringify(finalParam);
localStorage.setItem("selectedDevicesConfigSync", paramSelectedDevices);
if (selectedDevices.length !== finalParam.length) {
toast({
message: finalParam.length + i18n.device_out_of_sync_for_start_vs_run,
flavor: "warning",
label: i18n.toast_header_running_configuration
});
}
shell.router.push(`/dna/provision/configuration-compliance`);
}
};
const getDeviceRunningCompliance = (selectedDevices) => {
let self = this;
let deviceRunningComplaince = [];
selectedDevices.forEach((val, index) => {
let obj = {};
getComplianceDetails(val.id).then(data => {
const complianceDetailsData = data;
if (complianceDetailsData) {
// this.setState({
// complianceDetailsData: data
// });
let cardStatus;
let complianceApiDataForConfig =
complianceDetailsData && complianceDetailsData.filter(config => config.complianceType === "RUNNING_CONFIG");
cardStatus =
complianceApiDataForConfig && complianceApiDataForConfig.length && complianceApiDataForConfig[0].status;
obj.id = val.id;
obj.runningStatus = cardStatus;
deviceRunningComplaince.push(obj);
// return cardStatus;
}
});
// deviceRunningComplaince.push(obj);
});
return deviceRunningComplaince;
};
This is how I solved this issue. Please comment if we can do this better.
/**
* #param {*} graphTable
*/
const runConfigComplianceDeviceOnClick = graphTable => {
let selectedDevices = graphTable.dTable.store.state.selectedRowsData;
let paramSelectedDevices;
let filteredSelectedDevices;
let finalParam;
let supportedDevices = true;
getDeviceRunningCompliance(selectedDevices).then(function(some) {
if (some.length) {
filteredSelectedDevices = selectedDevices.map(function(device, index) {
console.log("getDeviceRunningCompliance some filteredSelectedDevices", some);
if (notSupportedFamilies.includes(device.series)) {
// console.log(i18n.no_support_available_for_aireos);
supportedDevices = false;
} else {
// console.log(i18n.label_configuration_data_not_available);
supportedDevices = true;
}
let valsss = some.find(x => x.id === device.id);
console.log("valsss ", valsss);
return {
id: device.id,
hostname: device.hostname,
val: device.complianceStoreStatus.complianceStatus,
collectionStatus: device.collectionStatus,
series: device.series,
supportedDevices: supportedDevices
};
});
finalParam = filteredSelectedDevices.filter(function(val, index) {
return val.supportedDevices && val.val === "NON_COMPLIANT"; // this should be enable
});
paramSelectedDevices = JSON.stringify(finalParam);
localStorage.setItem("selectedDevicesConfigSync", paramSelectedDevices);
if (selectedDevices.length !== finalParam.length) {
toast({
message: finalParam.length + i18n.device_out_of_sync_for_start_vs_run,
flavor: "warning",
label: i18n.toast_header_running_configuration
});
}
shell.router.push(`/dna/provision/configuration-compliance`);
}
});
};
const getDeviceRunningCompliance = selectedDevices => {
let promiseData = selectedDevices.map((val, index) => {
return getComplianceDetails(val.id).then(data => {
let obj = {};
const complianceDetailsData = data;
if (complianceDetailsData) {
let cardStatus;
let complianceApiDataForConfig =
complianceDetailsData && complianceDetailsData.filter(config => config.complianceType === "RUNNING_CONFIG");
cardStatus =
complianceApiDataForConfig && complianceApiDataForConfig.length && complianceApiDataForConfig[0].status;
obj.id = val.id;
obj.runningStatus = cardStatus;
return obj;
}
});
});
return Promise.all(promiseData);
};
I'm trying to create a function in node js which reads database values in and pushes them into an array, and then at the end returns this array. My functions looks like this at the moment:
function getInvoicesCount() {
let promiseInvoices = [];
let userInvCount = 0;
let deletedUserInvCount = 0;
let userInvAmount = 0;
let deletedUserInvAmount = 0;
let monthWiseInvCount = [];
db.userInvoices
.findAll({
attributes: [
'deleted_at',
[sequelize.fn('COUNT', sequelize.col('id')), 'count'],
[sequelize.fn('SUM', sequelize.col('invoice_amount')), 'amount'],
[sequelize.fn('MONTH', sequelize.col('invoice_date')), 'month']
],
group: ['invoice_date', 'deleted_at'],
paranoid: false
})
.then(result => {
result.forEach(function(element) {
userInvCount += element.dataValues.count;
userInvAmount += element.dataValues.amount;
if (element.dataValues.deleted_at != null) {
deletedUserInvAmount += element.dataValues.amount;
deletedUserInvCount += element.dataValues.count;
}
monthWiseInvCount.push(element.dataValues);
});
if (monthWiseInvCount.map(a => a === 'deleted_at')) {
monthWiseInvCount.map(a => delete a.deleted_at);
}
promiseInvoices.push(
userInvCount,
userInvAmount,
deletedUserInvCount,
deletedUserInvAmount,
monthWiseInvCount
);
});
return promiseInvoices;
}
In the main part of the code I would like to call this funtion and use a .then to get the returned array
Can you help me out how I can return a promise in the function and how will the array be accessible in the .then part?
Here are the changes you need to do to get expected result :
function getInvoicesCount() {
...
return db.userInvoices.findAll({ //<-------- 1. First add return here
...
}).then(result => {
...
return promiseInvoices; //<----------- 2. Put this line inside the then
});
// return promiseInvoices; //<----------- Remove this line from here
}
getInvoicesCount().then(data => {
console.log(data); // <------- Check the output here
})
Explanation for this :
To get .then when you can function , function should return promise ,
but in you case you are just returning a blank array ,
As per the sequlize doc , db.userInvoices.findAll returns the
promise so all you need to do is add return before the this function
, First step is done
You were return promiseInvoices; at wrong place , why ? , coz at
that you will never get the result , as the code above it run in async
manner as it is promise , so you will always get the balnk array , to
get the expected result you should return it from
db.userInvoices.findAll's then function as shown above in code
You should return the results from then to access it in the chain.
function getInvoicesCount() {
const promiseInvoices = []
let userInvCount = 0
let deletedUserInvCount = 0
let userInvAmount = 0
let deletedUserInvAmount = 0
const monthWiseInvCount = []
return db.userInvoices
.findAll({
attributes: [
'deleted_at',
[sequelize.fn('COUNT', sequelize.col('id')), 'count'],
[sequelize.fn('SUM', sequelize.col('invoice_amount')), 'amount'],
[sequelize.fn('MONTH', sequelize.col('invoice_date')), 'month'],
],
group: ['invoice_date', 'deleted_at'],
paranoid: false,
})
.then((result) => {
result.forEach((element) => {
userInvCount += element.dataValues.count
userInvAmount += element.dataValues.amount
if (element.dataValues.deleted_at != null) {
deletedUserInvAmount += element.dataValues.amount
deletedUserInvCount += element.dataValues.count
}
monthWiseInvCount.push(element.dataValues)
})
if (monthWiseInvCount.map(a => a === 'deleted_at')) {
monthWiseInvCount.map(a => delete a.deleted_at)
}
return promiseInvoices.push(
userInvCount,
userInvAmount,
deletedUserInvCount,
deletedUserInvAmount,
monthWiseInvCount,
)
})
}
You can now use
getInvoicesCount().then(() => {
//do something here
})
getData(htmlData,tags)
.then(function(data) {
console.log(data); //use data after async call finished
})
.catch(function(e) {
console.log(e);
});
function getData() {
return new Promise(function(resolve, reject) {
//call async task and pass the response
resolve(resp);
});
}
In general you can return a promise like this:
function returnPromise() {
return new Promise((resolve, reject) => {
resolve({foo: 'bar'});
});
}
So while the other answer is completely correct, you can use the above structure to create a function that returns a promise like this:
function getInvoicesCount() {
return new Promise((resolve, reject) => {
let promiseInvoices = [];
let userInvCount = 0;
let deletedUserInvCount = 0;
let userInvAmount = 0;
let deletedUserInvAmount = 0;
let monthWiseInvCount = [];
db.userInvoices
.findAll({
attributes: [
'deleted_at',
[sequelize.fn('COUNT', sequelize.col('id')), 'count'],
[sequelize.fn('SUM', sequelize.col('invoice_amount')), 'amount'],
[sequelize.fn('MONTH', sequelize.col('invoice_date')), 'month']
],
group: ['invoice_date', 'deleted_at'],
paranoid: false
})
.then(result => {
result.forEach(function(element) {
userInvCount += element.dataValues.count;
userInvAmount += element.dataValues.amount;
if (element.dataValues.deleted_at != null) {
deletedUserInvAmount += element.dataValues.amount;
deletedUserInvCount += element.dataValues.count;
}
monthWiseInvCount.push(element.dataValues);
});
if (monthWiseInvCount.map(a => a === 'deleted_at')) {
monthWiseInvCount.map(a => delete a.deleted_at);
}
promiseInvoices.push(
userInvCount,
userInvAmount,
deletedUserInvCount,
deletedUserInvAmount,
monthWiseInvCount
);
resolve(promiseInvoices); // When you are done, you resolve
})
.catch(err => reject(err)); // If you hit an error - reject
});
}
However that is a rather big function, would recommend splitting it up in smaller parts.
Is there a way to get rid of the this keyword on the line:
this.getOscillatorConfig(oscNumber);
below?:
const oscPlayer = (audioContext, voiceConfig) => ({
getOscillatorConfig(oscNumber)
{
return voiceConfig.oscillators[oscNumber];
},
getOscillator(oscNumber)
{
this.getOscillatorConfig(oscNumber);
let vco = audioContext.createOscillator();
vco.type = oscConfig.waveform;
return vco;
},
start: (vco, time, noteLength, frequency) => {
vco.frequency.value = frequency;
vco.start(time);
vco.stop(time + noteLength);
}
});
const octave = () => ({
applyPipeLength: (frequency, pipeLength) => {
return frequency / (parseInt(pipeLength, 10) / 8);
}
});
const Voice = (audioContext, voiceConfig) => {
return Object.assign(
{},
oscPlayer(audioContext, voiceConfig),
octave()
)
}
If I don't use it, I have getOscillatorConfig is undefined.
Or any other advice for how to structure this?
To be able to omit this, you have to create a function with name getOscillatorConfig that is available in the scope you want to call it:
const oscPlayer = (audioContext, voiceConfig) => {
function getOscillatorConfig(oscNumber) {
return voiceConfig.oscillators[oscNumber];
}
return {
getOscillator(oscNumber) {
getOscillatorConfig(oscNumber);
let vco = audioContext.createOscillator();
vco.type = oscConfig.waveform;
return vco;
},
start(vco, time, noteLength, frequency) {
// ...
}
};
};