Home > Back-end >  How can I do a async function over and over?
How can I do a async function over and over?

Time:09-17

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)
}

CodePudding user response:

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);
  }
})();

CodePudding user response:

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