async function generateNextNrOf() {
const companyOf = await Company.find().limit(1).sort({ $natural: -1 });
const now = new Date();
const month = now.getUTCMonth() + 1;
const year = now.getUTCFullYear();
let poprzedniNr = companyOf[0].nrOf;
let checkingTab = [];
checkingTab = poprzedniNr.split('/');
if (month === parseFloat(checkingTab[0])) {
let newNumber = `${month}/${year}/Of/${parseFloat(checkingTab[3]) + 1}`;
console.log(newNumber);
return newNumber;
} else {
let newNumber = `${month}/${year}/Of/1`;
console.log(newNumber);
return newNumber;
}
}
I checking from MongoDB last record, I am looking for a variable named "nrOf" (4/2022/Of/1).
I try generate next number like 4/2022/Of/2 and so on and so forth.
If I try run generateNextNrOf(); I only get the Promise, but i need this result "pass" to variable, like const exampleVariable = '4/2022/Of/2';
I know async/await always return a Promise, but probably is the solution for my case.
async function generateNextNrOf() {
const companyOf = await Company.find().limit(1).sort({ $natural: -1
});
const now = new Date();
const month = now.getUTCMonth() + 1;
const year = now.getUTCFullYear();
let poprzedniNr = companyOf[0].nrOf;
let checkingTab = [];
checkingTab = poprzedniNr.split('/');
if (month === parseFloat(checkingTab[0])) {
let newNumber =
`${month}/${year}/Of/${parseFloat(checkingTab[3]) + 1}`;
console.log(newNumber);
return newNumber;
} else {
let newNumber = `${month}/${year}/Of/1`;
console.log(newNumber);
return newNumber;
}
}
I think you are calling this function from non-async function.Like this--
function main(){
const exampleVriable = await generateNextNrOf();
console.log(exampleVriable);
}
So the problem is main is not an async function ,thus you cannot use await in main. To solve this problem you must use async keyword before main.Here is the solution.
async function main(){
const exampleVriable = await generateNextNrOf();
console.log(exampleVriable);
}