可以使用内置的fetch()来简化这个异步代码吗?

huangapple go评论65阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年1月4日 01:03:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/59582484.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定