为什么两个函数不记录相同的结果?

Why don't both functions log the same result?

第一个示例记录了提取中承诺的解析值。
第二个示例将待处理的承诺对象记录到控制台,然后我必须 .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));

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

异步之外的任何内容都将照常在 运行 上继续。所以 console.log(getWeather(city, apiKey) 保持 运行 即使那个函数还没有得到响应。有几个解决方案。首先,您可以等待 getWeather,这需要将其包装在一个函数中。

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

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

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 是异步的,它将等待响应,同时 return 是一个承诺。但是 console.log 不是异步的。所以 console.log 像往常一样保持 运行,但是它只收到了来自 getWeather 的 Promise,因为那个函数没有被解析。

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

异步函数 return 承诺并且由于 console.log 不是异步函数,它不会等待 getWeather() 解析并且只会记录挂起

希望一切顺利

我建议只使用 .then()

 //you could do 
getWeather(city,ApiKey).then((response) =>{console.log(response));

希望对您有所帮助