大家!
我有一个小问题。我需要获取两个API:我需要调用第一个API,然后在第二个API中使用第一个API中的信息。您能帮我解决问题吗?这是我当前的代码,但是我不能以某种方式获取第一次获取的结果(可以在控制台和东西中看到,所以这不是问题;我只需要从那里获取数据)。
function App() {
const [query, setQuery] = useState('');
const [weather, setWeather] = useState({});
const search = evt => {
if (evt.key === "Enter") {
fetch(`${api.base}forecast?q=${query}&units=metric&APPID=${api.key}`)
.then(res => res.json())
.then(result => {
setWeather(result);
setQuery('');
console.log(result);
})
.then((result) => {
const data = fetch(`${api.base}onecall?lat=${result.city.coord.lat}&lon=${result.city.coord.lon}&APPID=${api.key}`)
console.log(data)
})
}
}
您需要返回in的结果then
,promise
因为它会根据返回的值创建一个新的promise。
const search = evt => {
if (evt.key === "Enter") {
fetch(`${api.base}forecast?q=${query}&units=metric&APPID=${api.key}`)
.then(res => res.json())
.then(result => {
setWeather(result);
setQuery('');
console.log(result);
return result; // add return statement
})
.then((result) => {
const data = fetch(`${api.base}onecall?lat=${result.city.coord.lat}&lon=${result.city.coord.lon}&APPID=${api.key}`)
data.then((res)=>res.json())
.then(result=>{
console.log(result)
})
})
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句