【发布时间】: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));
【问题讨论】:
-
你可能还需要等待
getWeather...
标签: javascript async-await fetch-api