首页 > 解决方案 > 为什么两个函数不记录相同的结果?

问题描述

第一个示例记录了 fetch 的 promise 的解析值。
第二个示例将待处理的 Promise 对象记录到控制台,然后我必须.then((res) => {console.log(res)})获得解析的值。

我正在使用异步函数,所以我认为这两个例子是等价的......?

我没有显示我的 API 密钥,但是当我在代码中使用它时它可以工作。

第一个例子:

const apiKey = 'somekey';
const city = 'Berlin'

const getWeather = async (cityArg, apiKeyArg) => {
    let city = cityArg;
    let apiKey = apiKeyArg;
    try{
        const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`);
        if(response.ok) {
          let jsonResponse = await response.json();
            console.log(jsonResponse);
            //return jsonResponse;
        }
    } catch(error) {
        console.log(error);
    }
}

getWeather(city, apiKey);
//console.log(getWeather(city, apiKey));

第二个例子:

const apiKey = 'somekey';
const city = 'Berlin'

const getWeather = async (cityArg, apiKeyArg) => {
    let city = cityArg;
    let apiKey = apiKeyArg;
    try{
        const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`);
        if(response.ok) {
          let jsonResponse = await response.json();
            //console.log(jsonResponse);
            return jsonResponse;
        }
    } catch(error) {
        console.log(error);
    }
}

//getWeather(city, apiKey);
console.log(getWeather(city, apiKey));

标签: javascriptasync-awaitfetch-api

解决方案


原因是您在该异步函数中等待,而不是在底部的 console.log 中等待。

该异步之外的任何内容都将继续正常运行。因此,console.log(getWeather(city, apiKey)即使该功能尚未得到响应,它也会继续运行。有几个解决方案。首先,您可以等待 getWeather,这需要将它包装在一个函数中。

await function secondFunc(){
    console.log(await getWeather(city, apiKey));
}
secondFunc();

在我看来,更好的方法是使用.then. 我几乎总是使用它,它对我来说更干净,更合乎逻辑。不要忘记您可以链接承诺声明。

fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`)
    .then(response => response.json())
    .then((response)=>{
        console.log(response);
        //Other code to do stuff with the response
    })
    .catch((error)=>{
        console.log(error);
    });

另一种思考方式是它getWeather是异步的,它将等待响应,同时返回一个承诺。但console.log不是异步的。所以console.log继续像往常一样运行,但它只收到了一个 Promise getWeather,因为该函数没有解析。

希望这很清楚。如果您不太明白,请告诉我,我会尽力进一步解释。


推荐阅读