0

I build a login function and check the credentials on my backend-server. I have to wait for the response of the server. I have used an official guide to es7-async-await.js, but it does not work. I have tried everything that async/await and promises give, but it does not work at all. I read all the posts regarding this issue. What am I doing wrong?

My function:

async getCredentials(pUser, pCipher) {

  var url = new URL(serviceURL);
  var params = {
    user: pUser,
    p: pCipher
  }
  Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))

  // await response of fetch call
  let response = await fetch(url, {
    method: 'get',
    headers: { }
  });
  // only proceed once promise is resolved
  let data = await response.json();
  // only proceed once second promise is resolved
  return data;
},

my function call:

this.getCredentials(this.input.username, cipher)
  .then(data => this.checkResponse = data.items)
  .catch(reason => console.log(reason.message))

console.log("data:  ->>>> " ,this.checkResponse);

the result:

enter image description here

data is always empty because the function does not wait

gianluca aguzzi
  • 1,734
  • 1
  • 10
  • 22
Ralf Bordé
  • 333
  • 4
  • 18
  • 1
    oh, wait ... your `console.log("data: ->>>> " ,this.checkResponse);` is run before the fetch even begins - since the fetch is asynchronous and you're not waiting for it to complete before the console.log - you need to realise code **after** .then/.catch doesn't wait – Jaromanda X Apr 22 '21 at 07:20

1 Answers1

0

can you put the console.log in the .then?. Is printing something?. If you do a console.log when the data is not received will not print anything.

this.getCredentials(this.input.username, cipher)
.then(data => 
    {
        this.checkResponse = data.items
        console.log("data:  ->>>> " ,this.checkResponse);       
    })
.catch(reason => console.log(reason.message))
alpachino
  • 79
  • 5
  • now it is working perfect in the function "data: ->>>> OK" But when I want to access the variable this.checkResponse after , the variable is empty again – Ralf Bordé Apr 22 '21 at 07:29
  • 1
    @RalfBordé It's not 'after' where you try to use it, it's 'before'. – Estus Flask Apr 22 '21 at 07:52
  • @Estus Flask: i want to access the variable after the .catch. Then the variable is empty: ... .catch((reason) => console.log(reason.message)); console.log("data: 2 ->>>> ", this.checkResponse); – Ralf Bordé Apr 22 '21 at 08:03
  • 1
    You were using the variable before receive the data. When you do your get the javascript code continue executing and arrive to the console.log wich is empty because the get is not completed yet. If you want to call a method or use the router to complete the login you should do it when your get is completed, so you should put it in the then. – alpachino Apr 22 '21 at 08:04
  • @alpacino: OK, i understand. I will put my logic in the .then. THX a lot. – Ralf Bordé Apr 22 '21 at 08:12