1

I'm using the fetch API to retrieve data. This is my code.

getUserYguid(){
        fetch(this.myapi, {
          credentials: "include",
          method: 'get',
          headers: {
          "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
        },
        body: null
        }).then(function(response){
            // if(response.start !== 200){
            //   return;
            // }
            response.json().then(function(json){
                //console.log(json);
                return new User(json.id, json.email, json.givenName, json.familyName);
                //console.log(user);
                //return user;
            })

        }).catch(function(error){
            console.log('Request failed', error);
      });
  }

From the response object, I can construct an User object and console.log it inside the response then. However later when I make a call like this.

let user = authenticator.getUserYguid();//Authenticator is the class housing the method.

I get undefined. How do I return the User object from the response and retrieve it outside.

  • `var somevar = getUser... ` Use that – Mihai Nov 02 '16 at 22:45
  • Presumably, `fetch` returns a promise so return that, same for `response.json` – Phil Nov 02 '16 at 22:46
  • @Phil so are you suggesting I write a separate function to convert the json data to User? –  Nov 02 '16 at 22:50
  • No, you just need to return the promises generated in your code, specifically from `fetch()` and `response.json().then()` – Phil Nov 02 '16 at 22:52
  • I'm rank new to javascript, and though the pointed page contains a lot of relevant info, I'm even more confused now. –  Nov 02 '16 at 22:58

0 Answers0