使用回调测试fetch API时,为何返回的Promise处于Pending状态
问题根因
- 核心是三层Promise链路断裂,叠加同步执行时机错位,和fetch本身的行为无关:
- 第一处断链:
getJson内部的fetch Promise链,在最后一个.then块执行完回调后,没有将拿到的data透传到链式调用的返回值中,整段链的最终返回值为undefined,虽然流程能跑完,但结果没有沿着Promise链路向下传递。 - 第二处断链:传入
getJson的回调中编写的return test,属于该回调函数自身的返回值,既不会被getJson捕获,更不会穿透外层Promise链路。回调的执行和返回值传递是独立的,不会自动成为外层async函数的返回值。 - 第三处断链:
getAll作为async函数,仅执行了await getJson(...),没有显式将getJson的返回值作为自身结果return,哪怕getJson的链路跑通,getAll返回的Promise最终也只会resolve为undefined。 - 执行时机错位:在同步代码流中直接打印
getData.getAll()时,函数内部的网络请求仍处于异步等待阶段,打印瞬间拿到的自然是pending状态的Promise。即使代码逻辑完全正确,同步打印的时机也不可能拿到已完成状态的结果。
- 第一处断链:
修正方案
- 调整
getJson的Promise链,保证结果沿链路透传:async function getJson(url, callback) { const response = await fetch(url) const data = await response.json() console.log(data) if (callback) callback(data) // 显式把data return到Promise链上,避免断链 return data } - 调整
getAll的逻辑,显式把异步获取的结果return出去,不要让Promise链停在await步骤:let getData = { getAll: async function() { const data = await getJson('js/getJson/data.json', function(data) { console.log(data.photographers) // 这里的return仅对回调自身生效,对外层Promise无影响 return data.photographers }) // 显式把要返回的结果透到async函数的返回值中 return data.photographers } } - 正确获取Promise最终结果,不要在同步栈直接打印pending状态的对象:
// 链式调用取结果 getData.getAll().then(res => console.log('最终返回值:', res)) // 支持顶层await的环境可直接等待执行完成 // const finalRes = await getData.getAll() // console.log('最终返回值:', finalRes)
关键认知:async函数的返回值,完全由函数体内部的显式return语句决定,在传入的回调内编写return逻辑,不会影响外层Promise的状态和返回结果,这点很容易和传统错误优先的Node回调模式混淆。
内容的提问来源于stack exchange,提问作者raphael parodi
相关产品推荐
相关产品推荐

