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

JavaScript Promise入门问题:如何将坐标传递给天气数据获取函数

解决Promise链式调用中传递数据的问题

你当前代码里的.then(getWeatherData(weatherURL, coords, key))写法存在两个核心错误:

  • 直接执行了getWeatherData函数,而非将其作为回调传递给then方法。then需要接收一个函数,该函数会在前置Promise完成后触发,并自动接收Promise的返回结果作为参数。
  • 变量coords在此处未定义,它是getCoords的返回值,只能在then的回调函数内部获取。

下面提供两种可行的修正方案:

方案1:修正Promise链式调用写法

通过匿名函数接收getCoords返回的坐标数据,再传入getWeatherData:

generate.addEventListener("click", (e) => {
    e.preventDefault();

    const zip = document.getElementById("zip").value;
    const feelings = document.getElementById("feelings").value;

    if (zip !== "") {
        generate.classList.remove("invalid");
        getCoords(zipURL, zip, key)
            // 用匿名函数接收coords,再调用getWeatherData
            .then(coords => getWeatherData(weatherURL, coords, key))
            // 处理天气数据返回结果
            .then(weatherData => {
                console.log('天气数据:', weatherData);
                // 示例:将数据渲染到页面
                userInfo.textContent = `当前温度:${weatherData.main.temp}°C`;
            })
            // 统一捕获链式调用中的所有错误
            .catch(error => console.log('请求错误:', error));
    }
})

方案2:用async/await简化代码(可读性更强)

将点击事件处理函数声明为async,用await等待Promise完成,逻辑更线性直观:

generate.addEventListener("click", async (e) => {
    e.preventDefault();

    const zip = document.getElementById("zip").value;
    const feelings = document.getElementById("feelings").value;

    if (zip !== "") {
        generate.classList.remove("invalid");
        try {
            // 等待getCoords返回坐标数据
            const coords = await getCoords(zipURL, zip, key);
            // 将坐标传入getWeatherData并等待结果
            const weatherData = await getWeatherData(weatherURL, coords, key);
            
            console.log('天气数据:', weatherData);
            // 示例:结合心情渲染完整内容
            userInfo.textContent = `当前温度:${weatherData.main.temp}°C,你的心情:${feelings}`;
        } catch (error) {
            // 捕获所有请求过程中的错误
            console.log('请求错误:', error);
        }
    }
})

额外注意点

  • 部分天气API(如OpenWeatherMap)的经度参数为lon而非long,若你的API要求lon,需将getWeatherData中的${coords.long}改为${coords.lon},否则会导致请求失败。
  • async函数执行后默认返回Promise,因此getCoords和getWeatherData的返回值均为Promise对象。
  • 链式调用中的catch可以统一捕获整个流程的错误,你原有函数内的catch可保留用于单独捕获单个请求的错误,也可移除后统一用外层catch处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 06:05:20