React中useEffect内async/await调用为何处于pending状态?
React useEffect异步调用获取文本内容的解决方案
你碰到的问题核心是:response.text()本身是异步方法,返回的是Promise对象——哪怕你已经通过await fetch(...)拿到了响应对象,直接打印它依然会输出Promise,而不是解析后的实际文本。
方案一:用await二次等待文本解析
修改代码,对response.text()也使用await,确保等待它完成解析:
useEffect(() => { async function fetchConstitution() { const response = await fetch(constitution_text); const text = await response.text(); // 这里加上await获取实际文本 console.log(text); return response; } fetchConstitution(); }, []);
方案二:用.then()链式处理Promise
如果用.then()重构,需要在response.text()后追加链式调用,才能拿到实际文本:
useEffect(() => { fetch(constitution_text) .then(response => response.text()) .then(text => console.log(text)); }, []);
补充说明:await和.then()的作用本质是一致的,都是处理异步Promise的手段——await只是同步风格的语法糖,底层还是基于Promise实现的。
内容的提问来源于stack exchange,提问作者Jcipa
相关产品推荐
相关产品推荐

