Fetch returns promise instead of actual data even after using #39;then#39;(即使在使用 then 之后,Fetch 也会返回 promise 而不是实际数据)
问题描述
我正在我的组件中进行一个简单的 fetch 调用,看起来像这样
I am making a simple fetch call in my component, which looks like this
var x = fetch(SOME_URL, SOME_POST_DATA)
.then((response) => response.json())
.then((responseJSON) => {return responseJSON});
console.log(x);
调用成功执行,但控制台打印的是 promise 而不是数据.我在这里错过了什么?
The call executes successfully but the console prints a promise instead of data. What am I missing here?
推荐答案
promise 的工作方式意味着您需要处理 responseJSON
inside 的处理程序>然后()代码>.由于请求的异步特性,外部代码在 Promise 解决时已经返回.
The way promises works mean you'll need to handle the responseJSON
inside the handler for then()
. Due to the asynchronous nature of requests the outer code will already have returned by the time the promise resolves.
一开始可能很难理解,但它与传统"AJAX 请求大致相同 - 您在回调中处理响应.
It can be hard to get your head around at first, but it's much the same as a "traditional" AJAX request - you handle the response in a callback.
以你为例:
var x = fetch(SOME_URL, SOME_POST_DATA)
.then((response) => response.json())
.then((responseJSON) => {
// do stuff with responseJSON here...
console.log(responseJSON);
});
更多阅读:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
这篇关于即使在使用 'then' 之后,Fetch 也会返回 promise 而不是实际数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:即使在使用 'then' 之后,Fetch 也会返回 promise 而不是实际数据


- 400或500级别的HTTP响应 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07