JavaScript中如何正确获取fetch响应结果并将其赋值给变量
你遇到的问题是因为fetch是异步API,返回的是Promise对象,你的代码执行console.log(data)时,网络请求还没有完成,所以拿到的是pending状态的Promise,而非最终的响应数据。
所有需要用到接口返回数据的逻辑,都必须等待异步请求完成后再执行,有两种常用实现方式:
方式1:使用.then链式调用
把数据处理、DOM操作的逻辑都放到then的回调函数中:
fetch('http://localhost/api/products') .then(response => response.json()) .then(data => { // 此处可以正常拿到接口返回的data console.log(data) // 你的DOM操作逻辑写在这里即可 // 示例:document.querySelector('.product-name').innerText = data.name })
方式2:使用async/await语法(更易读)
将请求逻辑封装到async标记的异步函数中,用await等待异步操作完成:
// 声明异步请求函数 async function getProductData() { const response = await fetch('http://localhost/api/products') const data = await response.json() // 此处拿到返回数据 console.log(data) // 执行DOM操作逻辑 } // 调用函数发起请求 getProductData()
内容的提问来源于stack exchange,提问作者Ivandez
相关产品推荐
相关产品推荐

