【问题标题】:Why don't both functions log the same result?为什么两个函数不记录相同的结果?
【发布时间】:2021-07-30 02:27:34
【问题描述】:

第一个示例记录从 fetch 中解析出来的承诺值。
第二个示例将待处理的 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));

【问题讨论】:

标签: javascript async-await fetch-api


【解决方案1】:

原因是您在该异步函数中等待,而不是在底部的 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 继续像往常一样运行,但它只收到了来自getWeather 的 Promise,因为该函数没有解析。

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

【讨论】:

  • 我想我明白了,我正在记录从 getWeather 函数返回的承诺,然后它有机会解决?
【解决方案2】:

异步函数返回 Promise,并且由于 console.log 不是异步函数,它不会等待 getWeather() 解决,只会记录挂起

希望可以解决

id 建议只使用 .then()

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

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 2012-06-22
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 2017-01-11
    • 2010-10-30
    • 2015-10-10
    • 2023-02-25
    相关资源
    最近更新 更多