我怎樣才能反復執行一個異步函式?我試著在一個while回圈里做,但它只做了第一行,也就是console.log,其他什么都沒做。
import fs from 'fs-extra'/span>
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"/span>)
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"/span>)
var etherminegwei = await fetch('https://api.ethermine.org/poolStats'/span>)
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', '$'/span> price ' |' timeNow '
')
}
else {return}。
if (price <= 5) {
console.log(`Gas Price is $${price} at ${timeNow})
fs.appendFileSync('lowGasPrice.txt', '$'/span> price ' |' timeNow '
')
}
else {return }
}
while (true) {
gasFee()
wait(1500)
}
uj5u.com熱心網友回復:
你的wait函式不是一個基于承諾的異步函式,你需要改變它。 此外,你需要等待你的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"/span>)。
var ethprice = await fetch(
"https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd"/span>
);
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 "
")。
} else {
return;
}
if (price <= 5) {
console.log(`Gas Price is $${price} at ${timeNow}) 。
fs.appendFileSync(
"lowGasPrice.txt"。
"$"/span> price " |" timeNow "
"/span>
);
} else {
return;
}
}
(async function run() {
while (true) {
await gasFee()。
await wait(1500)。
}
})();
uj5u.com熱心網友回復:
為了贊美已接受的答案,你可以考慮使用內置的javascript函式setInterval()。
這需要一個函式作為回呼,每隔x毫秒執行一次。該函式回傳一個ID,可以用來在以后取消間隔時間:
這需要一個函式作為回呼,每隔x毫秒執行一次。
var gasFee = function () {
console.log("fetching ETH Price"/span>)。
//... 函式的其余部分
}
///每1500MS呼叫gasFee()。
var gasFeeIntervalID = setInterval(gasFee, 1500)。
//取消執行如果需要的話。
clearInterval(gasFeeIntervalID)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/318064.html
標籤:
上一篇:異步mosquitto客戶端試圖與mosquitto代理重新連接
下一篇:02 區塊鏈的安全和隱私
