Node.js中fetch()与async/await使用:如何获取响应体并向上传递
问题分析与解决方案
你的核心问题是异步操作的结果无法同步获取,makeCall().then(...)返回的仍然是一个Promise对象,所以直接打印callComplete(你代码里最后写成了retrieveResponse,应该是笔误)只会输出Promise,而不是最终的响应体。
为什么会这样?
JavaScript的异步操作是非阻塞的:当代码执行到console.log("Finally this log: ...")时,makeCall发起的网络请求还没完成,callComplete此时只是一个未被resolved的Promise,自然无法拿到最终结果。
修正方案
方案1:用async/await包裹主逻辑
把需要依赖异步结果的代码放到async函数里,用await等待Promise完成:
async function makeCall() { var restHostConfig = await fetch("https://httpbin.org/ip") var body = await restHostConfig.json(); console.log("First this: " + JSON.stringify(body)); return body; } // 新增主函数,用await获取异步结果 async function run() { const resolvedData = await makeCall().then((response) => { console.log("Now this: " + JSON.stringify(response)); return JSON.stringify(response); }); console.log("Finally this log: " + resolvedData); } run();
方案2:链式调用.then()
直接在现有then的后面追加新的then,把打印逻辑放在里面:
async function makeCall() { var restHostConfig = await fetch("https://httpbin.org/ip") var body = await restHostConfig.json(); console.log("First this: " + JSON.stringify(body)); return body; } makeCall().then((response) => { console.log("Now this: " + JSON.stringify(response)); return JSON.stringify(response); }).then(resolvedData => { // 在这里打印最终结果 console.log("Finally this log: " + resolvedData); });
简化版:直接在makeCall的await后处理
其实你可以把所有逻辑整合到async函数里,不需要额外的then:
async function makeCall() { const restHostConfig = await fetch("https://httpbin.org/ip") const body = await restHostConfig.json(); console.log("First this: " + JSON.stringify(body)); return body; } async function run() { const response = await makeCall(); const resolvedData = JSON.stringify(response); console.log("Now this: " + resolvedData); console.log("Finally this log: " + resolvedData); } run();
内容的提问来源于stack exchange,提问作者Justus Howey
相关产品推荐
相关产品推荐

