我正在尝试从呈现为HTML的API中获取数据。我通过以下方式向API发出请求:
const openWeatherMapApiUrl = "https://cors-anywhere.herokuapp.com/http://api.openweathermap.org/data/2.5/weather";
async function getWeatherData() {
try {
const response = await axios.get(openWeatherMapApiUrl, {
params: {
q: "London,uk",
appId: "956d289b64e4e226bdef9ce1f93b475b"
}
})
console.log(response.data);
return response.data;
} catch (error) {
console.error(error);
}
}
从那里,我使用以下命令将数据渲染到HTML中:
renderWeather = () => {
var template = document.getElementById('template').innerHTML;
var rendered = Mustache.render(template, {
cityName: getWeatherData()
});
document.getElementById('target').innerHTML = rendered;
}
代替呈现数据,它呈现[object Promise]
。我了解这可能是由于尚未兑现承诺,所以我也尝试通过以下方式兑现承诺:
getWeatherData().then((response) => {return response})
以及它在不同位置的不同变体,但是仍然返回相同的[object Promise]
响应。
答案 0 :(得分:0)
getWeatherData
返回一个需要await
来获取数据的promise,如果getWeatherData
内报告错误,则重新抛出该错误以通知调用者:
const openWeatherMapApiUrl = "https://cors-anywhere.herokuapp.com/http://api.openweathermap.org/data/2.5/weather";
async function getWeatherData() {
try {
const response = await axios.get(openWeatherMapApiUrl, {
params: {
q: "London,uk",
appId: "956d289b64e4e226bdef9ce1f93b475b"
}
})
console.log(response.data);
return response.data;
} catch (error) {
console.error(error);
throw error; // reject returned promise
}
}
如果在调用函数后要报告错误,则可以简化为
function getWeatherData() {
return axios.get(openWeatherMapApiUrl, {
params: {
q: "London,uk",
appId: "956d289b64e4e226bdef9ce1f93b475b"
}
})
}
}
在Promise链中进行调用或处理时,两个版本都需要await
版本
getWeatherData()
.then( data => console.log(data))
.catch( err => console.error(err));
将数据作为renderWeather
的参数来帮助从异步代码中调用它:
renderWeather = (weatherData) => {
var template = document.getElementById('template').innerHTML;
var rendered = Mustache.render(template, {
cityName: weatherData
});
document.getElementById('target').innerHTML = rendered;
}