JavaScript中如何将fetch请求获取的数据正确保存到变量中
问题原因
fetch 属于异步API,代码运行时会先发起网络请求,之后直接继续执行后续的同步代码也就是console.log(darth),此时请求还没有返回结果,darth数组还没被赋值,所以打印出来的是空数组,拿不到预期数据。
正确实现方案
方案1:在Promise的then回调中处理
所有需要用到请求返回数据的逻辑,都放到then回调内部执行,保证请求完成后再操作变量:
const SWAPI_URL = "https://random-word-api.herokuapp.com/word?number=10"; let darth = []; fetch(SWAPI_URL) .then(response => response.json()) .then(darthVaderObj => { darth.push(darthVaderObj); // 所有需要用到darth的逻辑都写在这里 console.log(darth); })
方案2:用async/await语法简化写法
将异步逻辑封装到async函数中,用await等待请求完成后再操作变量,可读性更高:
const SWAPI_URL = "https://random-word-api.herokuapp.com/word?number=10"; let darth = []; async function fetchData() { const response = await fetch(SWAPI_URL); const darthVaderObj = await response.json(); darth.push(darthVaderObj); // 后续使用darth的逻辑可写在这里,也可将darth return出去供外部使用 console.log(darth); return darth; } // 调用异步函数 fetchData();
如果需要在async函数外部获取返回的数据,可以搭配then使用:
fetchData().then(res => { // 此处的res就是请求完成后的darth数据 console.log('外部获取到的数据:', res); })
内容的提问来源于stack exchange,提问作者Prajwol Maharjan
相关产品推荐
相关产品推荐

