英文:
Can I reduce this asynchronous code using built in fetch()?
问题
出现了额外的then
方法。
我想要简化为:
getUser() {
const options = {
credentials: 'include'
};
fetch("/api/user", options)
.then((response) => {
console.log(response.json());
})
.catch((err) => {
});
}
而不仅仅是测试它是否有效,我想尝试理解为什么最初写成这种方式,以及它是否是良好的实践。
更新
为什么会有两个then
用于只有一个异步事件?
难道解析 JSON 不应该是一个简单的同步函数调用吗?
还是说这只是一个设计选择,我们可以将任何函数变成异步的?
英文:
There seems to be an extra then
method
getUser () {
const options = {
credentials: 'include'
};
fetch("/api/user", options)
.then((response) => {
return response.json();
})
.then((results) => {
console.log(results);
})
.catch((err) => {
});
I would like to reduce to:
getUser () {
const options = {
credentials: 'include'
};
fetch("/api/user", options)
.then((response) => {
console.log(response.json());
})
.catch((err) => {
});
Wrather than just test it out and see if it works I would like to try and understand why it was written the first way an if it is good practice.
Update
Why are their two promises for only 1 asynchronous event?
Should not parsing JSON be a simple synchronous function call?
Or is this just a design choice that we can make any function asynchronous?
答案1
得分: 2
response.json()
返回一个承诺。他们的版本会记录下该承诺的结果。而你的版本会记录下处于挂起状态的承诺对象,而不是它解析出的值。
英文:
response.json()
returns a promise. Their version logs out the result of that promise. Your version would log out the promise object in a pending state, not the value it resolves to.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论