出于审美原因,如何将 .then 表示法转换为异步函数

How to convert .then notation to an async function for aesthetic reasons in react

出于可读性目的,我正在尝试使用异步函数而不是 fetch().then() 表示法。这是代码。

fetch("https://api.spotify.com/v1/me", {
    headers: {
      Authorization: "Bearer " + accessToken
    }
  })
  .then(response => response.json())
  .then(data =>
    this.setState({
      user: {
        name: data.display_name,
        href: data.external_urls.spotify
      }
    })
  )
  .catch(error => console.log("Data async function"));

我试过了,但没用。

async function data() {
  const response = fetch("https://api.spotify.com/v1/me", {
    headers: {
      Authorization: "Bearer " + accessToken
    }
  });
  const data = response.json();
  this.setState({
    user: {
      name: data.display_name,
      href: data.external_urls.spotify
    }
  })
}

data().catch(error => console.log("Data async function"));

给你:

这是将代码转换为 async await 方式的方法:

const your_function = async () => { 
    try{
        const res = await fetch("https://api.spotify.com/v1/me", { // <--- MISSING await
            headers: {
            Authorization: "Bearer " + accessToken
            }
        })
        const data = await response.json(); // <--- MISSING await
        this.setState({
            user: {
                name: data.display_name,
                href: data.external_urls.spotify
            }
        })
    } catch(error) {
        console.log("Data async function"));
    }
}; 

NOTE : As per you updated code you are missing await before all promise function, you can compare it will above code snippet

I do suggest to cover all the code within try catch block whenever you are using async await