Issues arising from using async/await in conjunction with .then() in vue.js login function, causing fetch process not to wait for completion

I implemented a login function to verify credentials on my backend server, but I am facing an issue with waiting for the server response. Despite following the es7-async-await.js guide and trying various async/await and promise techniques, the function still does not work properly. I have searched multiple forums for solutions, but I cannot seem to figure out what I am doing wrong.

Here is 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]))

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

Here is how I call the function:

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

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

The outcome:

https://i.stack.imgur.com/tIyOj.png

The data always returns empty because the function does not wait for the response.

Answer №1

Have you thought about placing the console.log inside the .then block? It may help with debugging as it will only print something if the data is received successfully.

this.retrieveCredentials(this.input.username, decryption)
.then(result => 
    {
        this.responseData = result.items
        console.log("Response Data: ", this.responseData);       
    })
.catch(error => console.log(error.message))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error Message: Expecting an Object - Microsoft JScript Runtime Error in Node.js

I am starting my journey with Node JS and I encountered an unexpected error while running my code. Microsoft Jscript Runtime Error appeared, stating that "Object expected at line number 1". const fs = require('fs'); function FileObject () { thi ...

Building a Vue application with customized authentication for the Google Calendar API in JavaScript

Struggling with understanding the migration from GAPI to GIS in Vue? Google has provided a helpful document on this topic: https://developers.google.com/identity/oauth2/web/guides/migration-to-gis#server-side-web-apps Attempting to implement code from the ...

The technique of binding methods in React

When working with React.js, it's recommended to define your method binding in the constructor for better performance. Here's an example: constructor(props){ this.someFunction = this.someFunction.bind(this); } This approach is more efficient t ...

Encountering a white screen and MIME Type Error when attempting to deploy a Vite app on GitLab Pages

I am facing an issue while trying to deploy my Vite application on Gitlab Pages. The page only displays a blank screen and the following errors are shown: The CSS and JS files from the static directory cannot be loaded due to MIME type mismatch (X-Content ...

Visual Studio Code encounters a Node.js error stating "Module not found"

I have been struggling to run my Node.js program in VSCode. Despite trying various solutions found on StackOverflow, none of them seem to be working for me. I even attempted the Json file method, but unfortunately, that didn't work either. internal/mo ...

Having difficulty generating a footer for a page that includes a Material-UI Drawer component

Looking to create a standard full-width footer at the bottom of my page, I need help with the implementation. Utilizing the "Permanent drawer" from Material-UI Drawer for reference here. If you're interested in experimenting with it, CodeSandbox link ...

Utilizing a While Loop for SQL Queries in a Node.js Environment

So, I was attempting to iterate through an array using a while loop. I was able to successfully print a result from the SQL connection without the while loop, confirming that the query is working. However, when I tried to implement the same query within a ...

Move router parameters to separate files to streamline and organize code

I have encountered a bit of an issue. I currently have the following code in my routing.js file where I define both my parameter and route. I have moved the routes to a separate router instance in my routing.js file, but I am struggling to separate the par ...

Whenever my code is used within Google Sites, it triggers the opening of a new and empty tab

When using this code inside an HTML box in Google Sites, a problem arises. It seems to work perfectly fine in Internet Explorer and Chrome when saved to an HTML file. However, within Google Sites, it unexpectedly opens a new tab with no data. The code st ...

The jQuery UI accordion fails to function properly after refreshing the data

I am facing an issue with my HTML page where data is loaded dynamically into accordions. The accordion functionality is implemented inside a function, which is called at regular intervals to refresh the data. Initially, the accordion displays correctly, bu ...

Async/Await mishap

Could someone please explain why the code below is printing a blank result? I was expecting it to print "done" since I thought the await keyword would make the program wait for the promise to be resolved. Appreciate any help provided! let message = &apos ...

Tips for clearing text inputs in ReactJS

In my current Reactjs project using nextjs, I am facing an issue with clearing input fields after a click event. Below is the code snippet that I have been working on: <form onSubmit={handleSubmit}> <input type="text" ...

Exploring the functionality of Protractor testing in combination with Angular 2, focusing

I am currently developing an Angular 2 application and I require some information regarding unit testing with Protractor. Previously, in Angular 1, we were able to check for things like: element(by.css('[ng-click="myFunction()"]')) in our test ...

Restricting the scope of reactivity in a VueJS data store

Goal: I am attempting to create an array of objects retrieved through an API call. After making the initial API call and receiving a single object, I want to store that result and then make another call without updating the original stored object. Challen ...

Malfunction in triggering events within an Ajax Magnific popup feature

I'm trying to load a page within a magnific popup using ajax: $("#operator").magnificPopup({ delegate: 'a.edit', mainClass: 'mfp-fade', closeBtnInside: true, removalDelay: 300, closeOnContentClick: false, t ...

I am looking to dynamically alter the CSS background URL using JavaScript

Currently, I am looking to update the background image url using JavaScript. Most tutorials I've come across involve having the image downloaded on the desktop and then providing its path. However, in my scenario, the user will input an image link whi ...

Unable to get the Gtranslate function to function properly within the drop-down menu

Currently, I am using Gtranslate.io languages on my website with flags displayed without a drop-down menu. Everything is running smoothly but now I am looking to enhance the user experience by placing the flags inside a drop-down list. I want English to ...

Steps to establish a connection with a remote MYSQL database using the actual IP address in Node.js

In my Nodejs file, I have set up the connection as follows. The issue arises when attempting to connect to the remote database on a server. module.exports = { host: '234.32432.32432',//this is an example IP address and not a real one. use ...

Passing Variables to Child Components with Vue Slots

Imagine creating a button component with a variable named myVar: MyButton.vue <template> <div> <slot :name="text"> My Button </slot> </div> </template> <script> export default { name: 'm ...

Controlling the back DIV while maintaining overlapping layers

I successfully positioned my right hand content on top of the leaflet map in the background using CSS properties like position and z-index. However, I am looking for a way to make the overlapping div not only transparent but also non-interactive while stil ...