我怎么能做一个异步函数一遍又一遍?



我怎么能做一个异步函数一遍又一遍?我试过在while循环中这样做,但它只做第一行,这是一个console.log,没有别的。

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 + 'rn')
}
else {return}
if (price <= 5) {
console.log(`Gas Price is $${price} at ${timeNow}`)
fs.appendFileSync('lowGasPrice.txt', '$' + price + ' | ' + timeNow + 'rn')
}
else {return}
}
while (true) {
gasFee()
wait(1500)
}

您的wait函数不是基于promise的异步函数,您需要更改它。此外,您需要等待getFee()函数来进行异步执行。

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 + "rn");
} else {
return;
}
if (price <= 5) {
console.log(`Gas Price is $${price} at ${timeNow}`);
fs.appendFileSync(
"lowGasPrice.txt",
"$" + price + " | " + timeNow + "rn"
);
} else {
return;
}
}
(async function run() {
while (true) {
await gasFee();
await wait(1500);
}
})();

要补充接受的答案,您可以考虑使用内置的javascript函数setInterval()。

这个函数作为回调函数,每x毫秒执行一次。该函数返回一个ID,可用于稍后取消间隔:

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

相关内容

  • 没有找到相关文章