How to return the json response from the fetch API

亡梦爱人 提交于 2019-12-07 12:30:14

问题


I have a function like so:

check_auth(){
    fetch(Urls.check_auth(), {
      credentials: 'include',
      method: 'GET'
    }).then(response => {
      if(response.ok) return response.json();
    }).then(json => {
      return json.user_logged_in;
    });
  }

And then I try to do this:

if(this.check_auth()){
    // do stuff
} else {
    // do other stuff
}

But, this.check_auth() is always undefined.

What am I missing here? I thought that within fetch's then() was where the resolved Promise object was therefore I thought that I'd get true when the user was logged in. But this is not the case.

Any help would be greatly appreciated.


回答1:


Async calls doesn't always resolve to be used anywhere within your app when you use .then(). The call is still async and you need to call your if-statement when you are calling your fetch. So anything that relies on the data you are fetching has to be chained to the fetch with .then().

  check_auth(){
        fetch(Urls.check_auth(), {
          credentials: 'include',
          method: 'GET'
        }).then(response => {
          if(response.ok) return response.json();
        }).then(json => {
          return json.user_logged_in;
        }).then(user => checkIfAuthSuccess(user)); //You have to chain it
      }

Wrapping your if-statement in a function or however your code looks like.

checkIfAuthSuccess(user){

  if(user){
     // do stuff
  } else {
    // do other stuff
  }
}

Nice video about async behavior in JavaScript: Philip Roberts: What the heck is the event loop anyway? | JSConf EU 2014




回答2:


Use callback

check_auth(callback){
    fetch(Urls.check_auth(), {
      credentials: 'include',
      method: 'GET'
    }).then(response => {
      if(response.ok) return response.json();
    }).then(json => {
      callback(json.user_logged_in);
    });
  }

 check_auth(function(data) {
        //processing the data
        console.log(d);
    });

In React it should be easier to handle, You can call a fetch and update the state, since on every update of state using setState the render method is called you can use the state to render

check_auth = () =>{
    fetch(Urls.check_auth(), {
      credentials: 'include',
      method: 'GET'
    }).then(response => {
      if(response.ok) return response.json();
    }).then(json => {
         this.setState({Result: json.user_logged_in});
    });
  }


来源:https://stackoverflow.com/questions/43454125/how-to-return-the-json-response-from-the-fetch-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!