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);
Related
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.
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);
}
does anyone have time to help me with a little problem? I did this function to check the license time but it doesn't really work, does anyone have any idea?
https://cdn.discordapp.com/attachments/953617052202074132/954398145868083291/unknown.png
https://cdn.discordapp.com/attachments/953617052202074132/954398654217723914/unknown.png
exilied_client.on('message', async message => {
if (message.content.startsWith(`${prefix}time`)) {
automex = message.author;
if(message.guild == undefined) {
message.reply("Comenzile le poti da doar pe server-ul de discord");
return;
};
if(message.member.roles.cache.has(zedu_roldiscord)) {
const argomento = message.content.slice(prefix.length).split(/ +/g)
const comando = argomento.shift().toLowerCase();
var i = 1;
if(argomento[0])
{
if(message.member.roles.cache.has(zedu_roldiscord))
{
var verificaretimp = message.guild.member(message.mentions.users.first() || message.guild.members.fetch(argomento[1]))
} else {
message.delete()
message.reply(automex.username + " Ce gatu ma-tii vrei sa faci?")
return;
}
} else {
var verificaretimp = automex
}
const Verificare = `SELECT license, used, total_time FROM licenses WHERE userid = '${verificaretimp.id}';`
const autoreasd = querytxt => {
return new Promise((resolve, reject) => {
exilied_database.query(querytxt, (err, results, fields) => {
if (err) reject(err);
resolve([results, fields]);
});
});
};
const [results, fields] = await autoreasd(Verificare);
const Mappa1 = results.map(results => `${(results.used)}`);
const Mappa2 = results.map(results => `${(results.total_time)}`);
var TempoAttesa = parseInt (Mappa1, 10);
var TempoAttesa2 = parseInt (Mappa2, 10);
function ConvertireTimp(UNIX_timestamp){
var exilied_time = new Date(UNIX_timestamp * 1000);
var mesi = ['January','February','March','April','May','June','July','August','September','October','November','December'];
exilied_time.setDate(exilied_time.getDate() + TempoAttesa2);
var year = exilied_time.getFullYear();
var month = mesi[exilied_time.getMonth()];
var date = exilied_time.getDate();
var hour = exilied_time.getHours();
var min = exilied_time.getMinutes();
var sec = exilied_time.getSeconds();
var time = date + ' ' + month + ' ' + year + ' ' + hour + ":"+ min;
return time;
}
message.delete()
var convertireatimp = ConvertireTimp(TempoAttesa2)
var expirelicense = automex.send("**__Your License Expired On__**: \n" + "" + convertireatimp + " \n If Not See Date Your Key Is Expired")
} else {
automex.send("**You Dont Have A License Key**")
}
}
});```
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;
};
I'm new with async/await and I need a litle help.
What I would like to achive is to send and axios post request after a while loop finished.
How can I put the while loop in an async function and await for it?
This is the current code:
showResults: function () {
let vm = this;
let apiUrl = '/api/test';
let randomCallCount = Math.floor(Math.random() * (80 - 50 + 1) + 50);
let start = 1;
while (start <= randomCallCount) {
let randomChars = [...Array(40)].map(i => (~~(Math.random() * 36)).toString(36)).join('');
fetch('https://' + randomChars + '.ipleak.net/json/?query_type=mydns')
.then((resp) => resp.json())
.then(function (data) {
vm.dnsResult.push(data);
});
start++;
}
axios.post(apiUrl, {lat: vm.geoLat, lon: vm.geoLon, dns: vm.dnsResult})...
I thought maybe something like this, but this one is not working:
fetchDNSData: async function () {
let vm = this;
let promise = new Promise((resolve, reject) => {
let randomCallCount = Math.floor(Math.random() * (80 - 50 + 1) + 50);
let start = 1;
while (start <= randomCallCount) {
let randomChars = [...Array(40)].map(i => (~~(Math.random() * 36)).toString(36)).join('');
fetch('https://' + randomChars + '.ipleak.net/json/?query_type=mydns')
.then((resp) => resp.json())
.then(function (data) {
vm.dnsResult.push(data);
});
start++;
}
});
let result = await promise; // wait until the promise resolves (*)
return result;
},
showResults: function () {
let vm = this;
let apiUrl = '/api/test';
vm.fetchDNSData().then(
response => {
axios.post(apiUrl, {lat: vm.geoLat, lon: vm.geoLon, dns: vm.dnsResult})...
Any suggestion what can show me the right direction? :) Thanks a lot
If you are going to use async/await, you should not use then. Use await instead of then.
The below example should be what you need.
showResults: async function () {
let vm = this;
let apiUrl = '/api/test';
let randomCallCount = Math.floor(Math.random() * (80 - 50 + 1) + 50);
let start = 1;
while (start <= randomCallCount) {
let randomChars = [...Array(40)].map(i => (~~(Math.random() * 36)).toString(36)).join('');
const response = await fetch('https://' + randomChars + '.ipleak.net/json/?query_type=mydns');
const data = await response.json();
vm.dnsResult.push(data);
start++;
}
axios.post(apiUrl, {lat: vm.geoLat, lon: vm.geoLon, dns: vm.dnsResult})...