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

如何将这段Python空气质量指数查询代码成功转换为JavaScript?

如何将查询城市AQI的Python代码转换为JavaScript代码

当然可以,下面分浏览器端和Node.js端给出对应的JavaScript实现,逻辑和你的Python代码完全一致:

浏览器端实现(无需额外依赖)

浏览器环境自带fetch API,直接用异步函数实现:

async function aqiChecker(cityName) {
  const apiKey = "API_KEY"; // 替换成你的实际API密钥
  const url = `https://api.waqi.info/feed/${cityName}/?token=${apiKey}`;

  const response = await fetch(url);
  const jsonData = await response.json();
  const aqi = jsonData.data.aqi;
  return `The AQI in ${cityName} is ${aqi}`;
}

// 调用示例(浏览器中顶级await需在模块环境或async函数内)
aqiChecker("new york city").then(result => console.log(result));

Node.js端实现(按需安装依赖)

Node.js 18+版本已内置fetch,若使用更低版本,需先安装node-fetch包:

npm install node-fetch

代码实现如下:

// 低版本Node.js需导入依赖
// import fetch from 'node-fetch'; // ES模块语法
// const fetch = require('node-fetch'); // CommonJS语法

async function aqiChecker(cityName) {
  const apiKey = "API_KEY";
  const url = `https://api.waqi.info/feed/${cityName}/?token=${apiKey}`;

  const response = await fetch(url);
  const jsonData = await response.json();
  const aqi = jsonData.data.aqi;
  return `The AQI in ${cityName} is ${aqi}`;
}

// 调用示例
(async () => {
  const result = await aqiChecker("new york city");
  console.log(result);
})();

关键逻辑对应说明

  • Python的f-string对应JavaScript的模板字符串(反引号包裹,${}插入变量)
  • Python的requests.get()对应JS的fetch(),均用于发起HTTP GET请求
  • 解析JSON响应:Python用response.json(),JS用await response.json()(因fetch的json()方法返回Promise)
  • JS异步操作需用async/await或.then()处理,不同于Python的同步阻塞逻辑

额外优化建议

原Python代码未做错误处理,JS版本可添加try/catch捕获请求失败、数据缺失等异常:

async function aqiChecker(cityName) {
  const apiKey = "API_KEY";
  const url = `https://api.waqi.info/feed/${cityName}/?token=${apiKey}`;

  try {
    const response = await fetch(url);
    if (!response.ok) throw new Error(`请求失败:${response.status}`);
    const jsonData = await response.json();
    if (!jsonData.data?.aqi) throw new Error("未获取到有效AQI数据");
    return `The AQI in ${cityName} is ${jsonData.data.aqi}`;
  } catch (error) {
    return `查询失败:${error.message}`;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 23:50:32