如何将getLastMatchData函数的API返回值保存到函数外部?
问题原因与解决方案
你的核心问题是异步操作的结果无法同步获取,具体来说:
getLastMatchData内部调用了异步的fetch,但没有返回这个异步操作的 Promise 对象,导致函数默认返回undefined。- 异步操作的结果不能直接用同步赋值的方式获取,必须通过 Promise 的链式调用或
async/await语法处理。
修复方案1:返回 Promise 并使用 .then 接收结果
修改函数,让它返回整个 fetch 的 Promise 链,然后在外部用 .then 获取结果:
import fetch from "node-fetch"; const premier_League_Id = '39' const tottenhamId = '47' const options = { method: 'GET', headers: { 'X-RapidAPI-Key': 'REDACTED', 'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com' } }; function getLastMatchData() { // 关键:返回整个异步操作的Promise链 return fetch('https://api-football-v1.p.rapidapi.com/v3/fixtures?season=2022&team=47&last=1', options) .then(response => response.json()) .then(data => { const generalLastMatchData = data['response']; const teamNames = generalLastMatchData[0]['teams']; const homeTeam = teamNames['home'].name; const awayTeam = teamNames['away'].name; return [homeTeam, awayTeam]; }) .catch(err => { // 必须处理错误,避免异步报错被静默吃掉 console.error('获取数据失败:', err); throw err; }); } // 外部通过.then接收异步结果 getLastMatchData().then(lastMatchNames => { console.log(lastMatchNames); // 在这里可以用lastMatchNames执行后续逻辑 });
修复方案2:使用 async/await 语法(更直观)
用 async/await 替代链式调用,让异步代码看起来像同步代码:
import fetch from "node-fetch"; const premier_League_Id = '39' const tottenhamId = '47' const options = { method: 'GET', headers: { 'X-RapidAPI-Key': 'REDACTED', 'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com' } }; async function getLastMatchData() { try { const response = await fetch('https://api-football-v1.p.rapidapi.com/v3/fixtures?season=2022&team=47&last=1', options); const data = await response.json(); const generalLastMatchData = data['response']; const teamNames = generalLastMatchData[0]['teams']; const homeTeam = teamNames['home'].name; const awayTeam = teamNames['away'].name; return [homeTeam, awayTeam]; } catch (err) { console.error('获取数据失败:', err); throw err; } } // 注意:await只能在async函数内部使用 async function main() { const lastMatchNames = await getLastMatchData(); console.log(lastMatchNames); } main();
关键要点总结
- 异步函数必须返回 Promise,才能在外部获取其执行结果。
- 不能用同步赋值(
const lastMatchNames = getLastMatchData())直接获取异步结果,必须用.then或await。 - 永远要添加错误处理(
catch或try/catch),避免网络请求失败时无任何反馈。
内容的提问来源于stack exchange,提问作者MadeInUtrecht
相关产品推荐
相关产品推荐

