You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何循环重复执行async异步函数?while循环调用仅执行首行console.log如何解决

问题根因

  • 自定义的wait是同步阻塞函数,会完全卡住JavaScript单线程的事件循环,gasFee中await后的异步回调没有执行时机,所以只能输出第一行打印内容,后续逻辑全部无法运行。
  • 循环中直接调用async函数没有加await,循环不会等待异步任务执行完成就直接进入下一轮,会造成大量异步任务堆积,逻辑完全乱序。
  • 现有逻辑存在短路问题:第一个if(price>5)后的else {return}会直接拦截所有price<=5的情况,后面的判断分支永远不会执行。
  • 数值运算优先级错误:21000 .toFixed(2)的写法会先执行toFixed方法再做乘法运算,最终得到的price值完全不符合预期。

修复代码

import fs from 'fs-extra'
import fetch from 'node-fetch'

// 替换为异步非阻塞等待函数
function wait(milliseconds) {
  return new Promise(resolve => setTimeout(resolve, milliseconds))
}

async function gasFee() {
    console.log("fetching ETH Price")
    const ethprice = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd')
    const ethPriceJSON = await ethprice.json()
    console.log("fetching Ethermine GWEI")
    const etherminegwei = await fetch('https://api.ethermine.org/poolStats')
    const ethermineGweiJSON = await etherminegwei.json()
    const ethPrice = ethPriceJSON.ethereum.usd
    const ethermineGwei = ethermineGweiJSON.data.estimates.gasPrice
    const gweiPrice = ethPrice / 1000000000
    // 修正运算优先级,先算完整乘积再调用toFixed
    const price = (ethermineGwei * gweiPrice * 21000).toFixed(2)
    const timeNow = new Date()
    if (price > 5) {
        console.log("Gas Price Logged")
        fs.appendFileSync('gasPrice.txt', '$' + price + ' | ' + timeNow + '\r\n')
    } else {
        console.log(`Gas Price is $${price} at ${timeNow}`)
        fs.appendFileSync('lowGasPrice.txt', '$' + price + ' | ' + timeNow + '\r\n')
    }
}

// 用异步自执行函数包裹循环,保证每一轮都等待异步逻辑执行完成
;(async () => {
  while (true) {
    await gasFee()
    await wait(1500)
  }
})()

内容的提问来源于stack exchange,提问作者Fisheiyy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 19:06:01