How to call Asyn function in another async function - javascript

How can I convert the below function into the Async function? I have to call few methods based on the outcome of the below function call once isMaxAttemptExceeded is fully executed.
let isMaxAttemptExceeded = () => {
console.log('called');
let ret = MyProfileRepository.getProfileByUserID(userEmail);
ret.then(function (response) {
//some verification here
if (userVerifiedCount >= 3) {
var curDate = moment(new Date().toISOString());
var diff = curDate.diff(nextDate, 'seconds');
if (diff > 0) {
console.log('diff - ' + diff);
setMSG(
'You have exceeded maximum allowed limit.Please try after ' +
diff / 60 +
' minutes'
);
return true;
} else {
return false;
}
} else {
return false;
}
});
};

You don’t save the then result so currently it’s useless, but if you want to return the then result it would look like this:
let isMaxAttemptExceeded = async () => {
console.log('called');
let response = await MyProfileRepository.getProfileByUserID(userEmail);
//some verification here
if (userVerifiedCount >= 3) {
var curDate = moment(new Date().toISOString());
var diff = curDate.diff(nextDate, 'seconds');
if (diff > 0) {
console.log('diff - ' + diff);
setMSG(
'You have exceeded maximum allowed limit.Please try after ' +
diff / 60 +
' minutes'
);
return true;
} else {
return false;
}
} else {
return false;
}
};
And a cleaned version:
let isMaxAttemptExceeded = async () => {
console.log('called');
let response = await MyProfileRepository.getProfileByUserID(userEmail);
//some verification here
if (userVerifiedCount < 3)
return false;
}
var curDate = moment(new Date().toISOString());
var diff = curDate.diff(nextDate, 'seconds');
if (diff <= 0) {
return false;
}
console.log('diff - ' + diff);
setMSG(`You have exceeded maximum allowed limit.Please try after ${diff / 60} minutes`);
return true;
};

Related

Sleep Debt Calculator, Why isn't this function working?

const getSleepHours = (day) => {
switch (day) {
case "monday":
return 6;
break;
case "tuesday":
return 7;
break;
case "wednesday":
return 9;
break;
case "thursday":
return 8;
break;
case "friday":
return 9;
break;
case "saturday":
return 10;
break;
case "sunday":
return 8;
break;
default:
console.log("Error");
}
};
console.log(getSleepHours("sunday")); // should print the # hours assigned to tuesday
const getActualSleepHours = () => {
const totalHours =
getSleepHours("monday") +
getSleepHours("tuesday") +
getSleepHours("wednesday") +
getSleepHours("thursday") +
getSleepHours("friday") +
getSleepHours("saturday") +
getSleepHours("sunday");
return totalHours;
};
const getIdealSleepHours = (idealHours) => idealHours * 7;
//console.log(getActualSleepHours());
//console.log(getIdealSleepHours());
const calculateSleepDebt = () => {
const actualSleepHours = getActualSleepHours();
const idealSleepHours = getIdealSleepHours(8);
const SleepDebt = idealSleepHours - actualSleepHours;
console.log(SleepDebt);
let time = '';
const SleepHourFunction = () => {
if (SleepDebt > 1) {
return time = ("hours");
} else if (SleepDebt < 1) {
return time = ("hours");
} else if (SleepDebt == 1) {
return time = ("hour");
} else {
return 'error';
}
}
SleepHourFunction();
if (actualSleepHours == idealSleepHours) {
console.log("You got the perfect amount of sleep. Keep it up!");
} else if (actualSleepHours > idealSleepHours) {
console.log(
"You got more sleep than neccessary. You are over by " + -SleepDebt + " " + time + "."
);
} else if (actualSleepHours < idealSleepHours) {
console.log(
"You need more sleep, get some rest. You are under by " + SleepDebt + " " + time + "."
);
} else {
console.log("Error");
}
};
calculateSleepDebt();
Here is the whole code.
const SleepDebt = idealSleepHours - actualSleepHours;
console.log(SleepDebt);
let time = '';
const SleepHourFunction = () => {
if (SleepDebt > 1) {
return time = ("hours");
} else if (SleepDebt < 1) {
return time = ("hours");
} else if (SleepDebt == 1) {
return time = ("hour");
} else {
return 'error';
}
}
SleepHourFunction();
This is what I tried. I am doing one of the Codecademy projects rn, almost finished, but I want to create a function where if the sleep debt hours is = 1, then it returns the singular term 'hour', and if it's multiple then returns the plural term 'hours'. It just keeps repeating hours regardless, I don't see why the function isn't executing how I want it. Does anybody have a clue? I am new to coding, so if this is a really simple problem, please be patient with me. Cheers.
.......................................
!UPDATE. played around with it and took in the feedback I figured it out
this is how I fixed it
if (SleepDebt > 1) {
return time = ("hours");
} else if (SleepDebt === 1 || SleepDebt === -1) {
return time = ("hour");
} else if (SleepDebt < 1) {
return time = ("hours");
} else {
return 'error';
}
SleepHourFunction();
Thanks so much for your answers guys it helped! :)

Node.JS Page only loads about 50% of the time

I have a function called parsedata in my node.js file which is called when a user logs in. After parsedata() is called, the server switches to a new screen. However, this only works every other time. I put an asynchronous wait in between, which made it work about 90% of the time but I am just wondering why it is doing this. I believe it has something to do with all of the helper functions which are being used but I am not completely sure. Any info or help would be greatly appreciated!
app.post("/login.html", urlencodedParser, async (req, res) => {
await parseData();
//await sleep(750);
res.redirect(__dirname + "/homescreen.html");
});
async function parseData() {
let dates = await findCommon();
let maxStreak = await getMaxStreak(dates);
}
async function findCommon() {
var dates = new Set();
var data = await fs.readFile(__dirname + "/mem.txt", "utf8", (err, data) => {
if (err) {
console.error(err);
return;
}
return data;
});
for (let i = 0; i < data.length; i++) {
if (data[i] === "*" && i + mostRecentName.length < data.length) {
if (data.slice(i + 1, i + mostRecentName.length + 1) == mostRecentName) {
while (data[i] != "\n") {
i++;
}
if (i < data.length - 1) {
i++;
}
while (data[i] != "*" && i < data.length) {
let curr = "";
let count = 10;
while (count > 0) {
count--;
curr += data[i];
i++;
}
while (data[i] != "\n") {
i += 1;
}
if (i < data.length - 1) {
i++;
}
dates.add(curr);
}
}
}
}
dates = Array.from(dates);
dates = await bubbleSort(dates);
return dates;
}
async function getMaxStreak(dates) {
let today = new Date();
let year = today.getFullYear().toString();
let month = (today.getMonth() + 1).toString();
let day = today.getDate().toString();
if (month.length == 1) {
month = "0" + month;
}
if (day.length == 1) {
day = "0" + day;
}
let testDate = year + "-" + month + "-"+ day;
if (!(testDate in dates)) {
dates.push(testDate);
}
let streak = 1;
for (let i = dates.length - 1; i > 0; i--) {
let options;
if (i == dates.length - 1) {
options = await convert(testDate);
} else {
options = await convert(dates[i]);
}
if (dates[i - 1] == options[0] || dates[i - 1] == options[1] || dates[i - 1] == options[2]) {
streak++;
} else {
return streak;
}
}
return streak;
}
async function convert(date) {
let option1Day = (parseInt(date.slice(8, 10)) - 1).toString();
if (option1Day.length == 1) {
option1Day = "0" + option1Day;
}
let option2Month = (parseInt(date.slice(5, 7)) - 1).toString();
if (option2Month.length == 1) {
option2Month = "0" + option2Month;
}
let option2Day = "30";
let option3Day = "31";
let option1 = date.slice(0, 8) + option1Day;
let option2 = date.slice(0, 5) + option2Month + "-" + option2Day;
let option3 = date.slice(0, 5) + option2Month + "-" + option3Day;
return [option1, option2, option3];
}
It has something with the macro and micro tasks.Your code has the same result with the following codes:
new Promise((resolve, reject) => {
findCommon().then(dates => {
getMaxStreak(dates).then(maxStreak => {})
})
resolve()
})
.then(() => {
res.redirect(__dirname + "/homescreen.html")
})
res.redirect will be added into the micro task queue;
then, getMaxStreak will be added into the micro task queue too.
finally, we will take out the first task of the micro task queue to execute, yes, it's res.redirect, not getMaxStreak.

How can I do a async function over and over?

How can I do an async function over and over? I have tried doing it inside a while loop but it only does the very first line which is a console.log and nothing else.
import fs from 'fs-extra'
import fetch from 'node-fetch'
function wait(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
}
async function gasFee() {
console.log("fetching ETH Price")
var ethprice = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd')
var ethPriceJSON = await ethprice.json()
console.log("fetching Ethermine GWEI")
var etherminegwei = await fetch('https://api.ethermine.org/poolStats')
var ethermineGweiJSON = await etherminegwei.json()
var ethPrice = ethPriceJSON.ethereum.usd
var ethermineGwei = ethermineGweiJSON.data.estimates.gasPrice
var gweiPrice = ethPrice/1000000000
var price = ethermineGwei * gweiPrice * 21000 .toFixed(2)
var timeNow = new Date()
if (price > 5) {
console.log("Gas Price Logged")
fs.appendFileSync('gasPrice.txt', '$' + price + ' | ' + timeNow + '\r\n')
}
else {return}
if (price <= 5) {
console.log(`Gas Price is $${price} at ${timeNow}`)
fs.appendFileSync('lowGasPrice.txt', '$' + price + ' | ' + timeNow + '\r\n')
}
else {return}
}
while (true) {
gasFee()
wait(1500)
}
Your wait function is not a promise-based async function and you need to change it.
Also, you need to await your getFee() function to make an async execution.
import fs from "fs-extra";
import fetch from "node-fetch";
const wait = ms => new Promise((resolve, reject) => setTimeout(resolve, ms));
async function gasFee() {
console.log("fetching ETH Price");
var ethprice = await fetch(
"https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd"
);
var ethPriceJSON = await ethprice.json();
console.log("fetching Ethermine GWEI");
var etherminegwei = await fetch("https://api.ethermine.org/poolStats");
var ethermineGweiJSON = await etherminegwei.json();
var ethPrice = ethPriceJSON.ethereum.usd;
var ethermineGwei = ethermineGweiJSON.data.estimates.gasPrice;
var gweiPrice = ethPrice / 1000000000;
var price = ethermineGwei * gweiPrice * (21000).toFixed(2);
var timeNow = new Date();
if (price > 5) {
console.log("Gas Price Logged");
fs.appendFileSync("gasPrice.txt", "$" + price + " | " + timeNow + "\r\n");
} else {
return;
}
if (price <= 5) {
console.log(`Gas Price is $${price} at ${timeNow}`);
fs.appendFileSync(
"lowGasPrice.txt",
"$" + price + " | " + timeNow + "\r\n"
);
} else {
return;
}
}
(async function run() {
while (true) {
await gasFee();
await wait(1500);
}
})();
To compliment the accepted answer, you might consider using the built-in javascript function setInterval().
This takes a function as a callback, which is executed each x milliseconds. The function returns an ID, that can be used to cancel the interval later:
var gasFee = function () {
console.log("fetching ETH Price");
// ... Rest of function
}
// Call gasFee() every 1500 MS
var gasFeeIntervalID = setInterval(gasFee, 1500);
// Cancel execution if needed
clearInterval(gasFeeIntervalID);

How to modify code so it doesn't run on reload?

This code,
function dec2hex(dec) {
return dec < 10 ? "0" + String(dec) : dec.toString(16);
}
function generateId(len) {
var arr = new Uint8Array((len || 40) / 2);
window.crypto.getRandomValues(arr);
return Array.from(arr, dec2hex).join("");
}
var random = generateId(64);
document.getElementById("password").innerHTML = random;
setInterval(function() {
function dec2hex(dec) {
return dec < 10 ? "0" + String(dec) : dec.toString(16);
}
function generateId(len) {
var arr = new Uint8Array((len || 40) / 2);
window.crypto.getRandomValues(arr);
return Array.from(arr, dec2hex).join("");
}
var random = generateId(64);
document.getElementById("password").innerHTML = random;
}, 5000);
<div id="password"></div>
will generate a random string every 5 seconds. However, it generate a new string when the page is reloaded. How can I make it NOT generate a random sting on a reload? I have not gotten anything with searches due to the limited queries.
You may use LocalStorage.
The code may look like :
var lastTimeGenerated = window.localStorage.getItem('lastTimeGenerated') === null
? false
: parseInt(window.localStorage.getItem('lastTimeGenerated'));
var generateInterval = 5000;
function dec2hex(dec) {
return dec < 10 ? "0" + String(dec) : dec.toString(16);
}
function generateId(len) {
var arr = new Uint8Array((len || 40) / 2);
window.crypto.getRandomValues(arr);
return Array.from(arr, dec2hex).join("");
}
function launchIntervalFnc() {
intervalFnc();
setInterval(intervalFnc, generateInterval);
}
function intervalFnc() {
var random = generateId(64);
document.getElementById("password").innerHTML = random;
window.localStorage.setItem('lastTimePassword', random);
window.localStorage.setItem('lastTimeGenerated', new Date().getTime());
}
if (lastTimeGenerated !== false && lastTimeGenerated + generateInterval > new Date().getTime()) {
document.getElementById("password").innerHTML = window.localStorage.getItem('lastTimePassword');
setTimeout(launchIntervalFnc, generateInterval - (new Date().getTime() - lastTimeGenerated));
} else {
launchIntervalFnc();
}
<div id="password"></div>

Javascript recursive function with defer not returning

I got this recursive function. I can see it loop through when data return is null but it did not return the promise when data is not null after done the recursive task. Seem like when finish doing the recursive task, the promise is lost somewhere. Would anyone point out what did I do wrong here?
var callrq1 = function(globalsystemid, globalgraphid, start, end, lastcheck) {
var datetimeformat = "YYYY-MM-DD HH:mm:ss";
var d1 = new $.Deferred();
var request1 = "../system/" + globalsystemid + "/highcharts.xml?type=" + globalgraphid + "&start=" + start + "&end=" + end;
var requeststring1 = makejson(request1); //this makejson function is an ajax get and return promise
requeststring1.done(function(data) {
if (data != null) {
d1.resolve(data);
} else {
var theend = moment(lastcheck).format(datetimeformat);
var newstart = moment(end).format(datetimeformat);
var newend = moment(end).add(1, 'weeks').format(datetimeformat);
if (newend <= theend) {
//recursive callrq1
callrq1(globalsystemid, globalgraphid, newstart, newend, theend);
} else {
d1.resolve(null);
}
}
});
return d1.promise();
}
callrq1(globalsystemid, globalgraphid, starttimeobj.start, starttimeobj.end, endtimeobj.start).then(function(data) {
console.log(data);
});
You missed resolving your deferred in the case of the recursive call. However, you shouldn't be using a deferred for this in the first place! Just chain a then callback and return the result promise from your function. You can even return promises from the callback, which we use for the recursive case:
function callrq1(globalsystemid, globalgraphid, start, end, lastcheck) {
var datetimeformat = "YYYY-MM-DD HH:mm:ss";
var request1 = "../system/" + globalsystemid + "/highcharts.xml?type=" + globalgraphid + "&start=" + start + "&end=" + end;
var requeststring1 = makejson(request1); //this makejson function is an ajax get and return promise
return requeststring1.then(function(data) {
//^^^^^^ ^^^^
if (data != null) {
return data;
// ^^^^^^
} else {
var theend = moment(lastcheck).format(datetimeformat);
var newstart = moment(end).format(datetimeformat);
var newend = moment(end).add(1, 'weeks').format(datetimeformat);
if (newend <= theend) {
return callrq1(globalsystemid, globalgraphid, newstart, newend, theend);
// ^^^^^^
} else {
return null;
// ^^^^^^
}
}
});
}
You are not resolving the deferred in the case of recursion
var callrq1 = function (globalsystemid, globalgraphid, start, end, lastcheck) {
var datetimeformat = "YYYY-MM-DD HH:mm:ss";
var d1 = new $.Deferred();
var request1 = "../system/" + globalsystemid + "/highcharts.xml?type=" + globalgraphid + "&start=" + start + "&end=" + end;
var requeststring1 = makejson(request1); //this makejson function is an ajax get and return promise
requeststring1.done(function (data) {
if (data != null) {
d1.resolve(data);
} else {
var theend = moment(lastcheck).format(datetimeformat);
var newstart = moment(end).format(datetimeformat);
var newend = moment(end).add(1, 'weeks').format(datetimeformat);
if (newend <= theend) {
//recursive callrq1
callrq1(globalsystemid, globalgraphid, newstart, newend, theend).done(function(data){
d1.resolve(data);//pass any data required
});
} else {
d1.resolve(null);
}
}
});
return d1.promise();
}
callrq1(globalsystemid, globalgraphid, starttimeobj.start, starttimeobj.end, endtimeobj.start).then(function (data) {
console.log(data);
});

Categories