我是javascript承诺的新手,所以我无法理解这一点



这是示例代码:

// Use zipURL to receive long and lat by using zipcode
const userInfo = document.getElementById('userInfo');
const generate = document.getElementById('generate');
// Function to get the coords using the zipcode entered in the form
const getCoords = async (zipURL, zip, key) => {
// res equals to the result of fetch function
const res = await fetch(`${zipURL}?zip=${zip}&appid=${key}`);
try {
// data equals to the result of fetch function
const coords = await res.json();
return coords;
}
catch (error) {
console.log("error", error);
}
};
// Function to get the weather data using the lat and long
const getWeatherData = async (weatherURL, coords, key) => {
const res = await fetch(`${weatherURL}?lat=${coords.lat}&long=${coords.long}&appid=${key}`);
try {
const data = await res.json();
return data;
}
catch (error) {
console.log("error", error);
}
}
generate.addEventListener("click", (e) => {
e.preventDefault();
const zip = document.getElementById("zip").value;
const feelings = document.getElementById("feelings").value;
if (zip !== "") {
generate.classList.remove("invalid");
getCoords(zipURL, zip, key)
.then(getWeatherData(weatherURL, coords, key))
}
})

我想接收coords,它是getCoords函数返回的promis对象中的经度和纬度。然后我想在getWeatherData函数中使用它们。但我似乎搞不懂这些小细节。请帮我解决这个问题,因为我一直在用头撞墙,让它发挥作用!

似乎不是向.then传递回调,而是传递函数执行。试试这个(我假设getCoords((的返回数据是属性为weatherURL, coords, key的对象(。或者使用异步等待语法而不是.then

generate.addEventListener("click", (e) => {
e.preventDefault();
const zip = document.getElementById("zip").value;
const feelings = document.getElementById("feelings").value;
if (zip !== "") {
generate.classList.remove("invalid");
getCoords(zipURL, zip, key)
.then(({weatherURL, coords, key}) => getWeatherData(weatherURL, coords, key))
}
})

相关内容

最新更新