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

CommonJS中async函数外使用await的替代方案及代码转换

CommonJS 中替代 ES 模块顶级 await 的解决方案(适配 ZDK NFT 数据获取)

CommonJS 不支持顶级 await,所有需要异步等待的逻辑必须包裹在 async 函数内部,通过**立即执行异步函数(IIFE)**或者手动调用异步函数处理结果。同时需要将 ES 模块的 import/export 语法替换为 CommonJS 的 require/module.exports,以下是针对你的代码的完整修改方案:

1. 修改 nftmodule.js(转为 CommonJS)

将顶级 await 逻辑放入 IIFE 中,确保异步数据初始化完成后再导出相关函数:

const { ZDK } = require('@zoralabs/zdk');

const zdk = new ZDK("https://api.zora.co/graphql");

async function fetchTokens(zdk, collectionAddresses) {
  return await zdk.tokens({
    where: {
      collectionAddresses
    }
  });
}

// 用立即执行异步函数处理 tokens 初始化
let tokens;
(async () => {
  tokens = await fetchTokens(zdk, '0x42069ABFE407C60cf4ae4112bEDEaD391dBa1cdB');
})();

// 若需确保 tokens 已加载完成,可将 aToken 改为异步函数
// async function aToken() {
//   if (!tokens) tokens = await fetchTokens(zdk, '0x42069ABFE407C60cf4ae4112bEDEaD391dBa1cdB');
//   return tokens;
// }

function aToken() {
  return tokens;
}

module.exports = { fetchTokens, aToken };

2. 修改 nftwholecollection.js(转为 CommonJS)

替换模块语法,将顶级 await 移入异步初始化逻辑,并调整 loopLinks 为异步函数确保数据就绪:

const { aToken, fetchTokens } = require('./nftmodule.js');
const { ZDK } = require('@zoralabs/zdk');

const zdk = new ZDK("https://api.zora.co/graphql");
const collectionSize = 40;
let nftGallery;

// 异步初始化数据
(async () => {
  // 测试获取单条 token 数据
  const token = await fetchTokens(zdk, '0x42069ABFE407C60cf4ae4112bEDEaD391dBa1cdB');
  const thistoken = JSON.stringify(token, null, 3);
  console.log(JSON.parse(thistoken).tokens.nodes[3].token.image);

  // 获取集合数据(若 aToken 改为异步函数需加 await)
  const tokens = await aToken();
  nftGallery = JSON.stringify(tokens, null, 3);

  // 初始化完成后调用测试
  console.log(await loopLinks());
})();

async function loopLinks() {
  // 确保数据已加载
  if (!nftGallery) {
    const tokens = await aToken();
    nftGallery = JSON.stringify(tokens, null, 3);
  }

  let output = "";
  const parsedGallery = JSON.parse(nftGallery);
  
  for (let x = 0; x < collectionSize; x++) {
    const mediaEncoding = parsedGallery.tokens.nodes[x].token.image.mediaEncoding;
    if (mediaEncoding.__typename !== "UnsupportedEncodingTypes") {
      output += `<img src="${mediaEncoding.thumbnail}" loading='lazy'>`;
    }
  }
  return output;
}

module.exports = { loopLinks };

3. 修改 nftrouter.js(转为 CommonJS)

将 Express 路由处理改为异步函数,等待 loopLinks 返回结果后再响应:

const { loopLinks } = require('./nftwholecollection.js');
const express = require('express');

const app = express();
const port = 5150;

// 异步路由处理器
app.get('/api/nft', async (req, res) => {
  res.setHeader("Content-Type", "text/html");
  const htmlOutput = await loopLinks();
  res.write(htmlOutput);
  res.end();
});

app.listen(port, () => {
  console.log("the server got 5150'd");
});

额外说明

  • 若你的 Node.js 版本 ≥14.8.0,可通过在 package.json 中设置 "type": "commonjs" 并添加 --experimental-top-level-await 参数启用顶级 await,但生产环境不推荐依赖实验特性。
  • 若后续要适配 React,无需转 CommonJS,直接在 React 组件的 useEffect 中调用异步函数获取 NFT 数据即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:40:50