即使在使用'then'后,Fetch也会返回promise而不是实际数据 [英] Fetch returns promise instead of actual data even after using 'then'
问题描述
我正在我的组件中进行一个简单的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?
推荐答案
Promises的工作方式意味着你需要处理 responseJSON
里面 的处理程序然后是()
。由于请求的异步性,外部代码已经在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而不是实际数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!