javascript - 为什么两个函数不记录相同的结果?
问题描述
第一个示例记录了 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));
解决方案
原因是您在该异步函数中等待,而不是在底部的 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
,因为该函数没有解析。
希望这很清楚。如果您不太明白,请告诉我,我会尽力进一步解释。
推荐阅读
- javascript - React 16.3 类方法与构造方法
- c# - C# windows store app / 使用 Windows.Graphics.Printing.PrintManager 以编程方式生成 PDF
- shiny - 如何在闪亮的仪表板中向 html 小部件添加工具提示
- selenium - 我们可以通过 UFT 执行/触发 selenium 自动化脚本吗
- typescript - 为什么在实现接口时需要显式键入我的方法参数?
- ssl - 最新开放的 SSL 不使用 tls?
- php - CodeIgniter 无法在 VPS 上发送电子邮件
- directshow - 任何区分虚拟和物理相机的方法
- javascript - 如何在 AMP 中多次渲染相同的元素?
- mongodb - UserNotFound:找不到用户 admin@automation