Search code examples
javascriptvue.jsasync-awaites6-promise

javascript/vue.js async/await and .then (promise) not waiting until completion of fetch in login function


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


Solution

  • 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))