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

What causes a Next.js App to crash when a prop is not defined in destructuring code?

Let me share the issue I am facing. I have developed a custom Context API wrapper to handle all my data. However, there is this docType property that may not always be defined or may not exist at times. When I destructure it in this way: const { docType } ...

Angular - Dividing Functionality into Multiple Modules

I am currently working with two separate modules that have completely different designs. To integrate these modules, I decided to create a new module called "accounts". However, when I include the line import { AppComponent as Account_AppComponent} from &a ...

Limiting the input in a text box to only allow whole numbers and no decimal values

What is the best way to limit a textbox to only accept whole numbers and exclude decimal values and alphabets? ...

What is the best way to incorporate an input id value (based on iteration) into a while loop that points to a specific piece of html located outside of the loop

In my scenario, I need to dynamically add input fields to a form based on the selection made in a dropdown. The issue arises when these new input fields end up sharing the same ID, which is causing problems in the code. To resolve this, I am looking to app ...

Issue with React: Children's state is altering the state of the parent component

Question : Why is it possible for a child component to change the state of its parent when each component has its own state? Below is the complete code for my app: import React, { Component } from 'react'; import { render } from 'react-do ...

What is the best way to merge several fetchMore functions within Apollo?

Can Apollo run multiple fetchMores simultaneously? I have a complex hook that executes two queries and combines their results into a single array. This is how it looks: export const useDashboardState = (collection: string) => { // Getting parameters ...

Is there a way to obtain a JWT token from a Node.js server without requiring an Ajax call from a Vue client?

I'm currently working on integrating Google-based authentication into my app. Here's an overview of what I've done so far: Utilizing the passport-google-oauth20 module to implement the Google strategy in my Express.js server. Created two e ...

Implementing a PayPal Payment Button in Vuejs3 using the Composition API setup function

Attempting to integrate PayPal buttons into my Vuejs3 project using the Composition API (setup), I encountered errors. When attempting integration without using setup, everything works perfectly fine. Below is the working script: <script> ...

Utilizing Angular to efficiently download and showcase PDF files

Presently utilizing https://github.com/stranger82/angular-utf8-base64 as well as https://github.com/eligrey/FileSaver.js/ for the purpose of decoding a base64 encoded PDF file that I am fetching from a rest API. It successfully decodes and downloads, ...

Routes for Express are throwing a 500 internal server error

My server is unable to locate the APIs that I have created in the API directory, which is resulting in a 500 internal server error. I have thoroughly checked routes.js and everything appears to be correct. Additionally, I have an error.js file for handlin ...

How to access a particular tab in Bootstrap 5 using an external link

Is there a way to direct users to a specific tab upon clicking a link on another page? Check out the example below: <div class="products-btn"> <a href="products.html#pills-profile">view all</a> </div> On Pro ...

Simple steps for retrieving URL parameters with AngularJS

HTML source code <div ng-app=""> <div ng-controller="test"> <div ng-address-bar browser="html5"></div> <br><br> $location.url() = {{$location.url()}}<br> $location.search() = {{$locati ...

Instructions on keeping a numerical counter at its current value for all site visitors

Recently, I integrated a number counter into my website. However, I am facing an issue where the count resets to zero whenever a new visitor accesses the site. I'd like the count to remain persistent and update based on the previous count. For instanc ...

Function utilizing variables parsed by Angular directive

I am currently working on a directive that I have created: feedBackModule.directive("responseCollection", ['deviceDetector', function (deviceDetector) { return { restrict: "E", templateUrl: 'js/modules/Feedback/direc ...

Strange symbols keep appearing in my output from PHP

My current task involves generating a SQL query based on some inputs. I have a predefined SQL statement, in which I perform certain replacements, that will use these inputs to generate the required SQL through an ODBC connection. For now, I have stored th ...

What is the best way to retrieve the outcome of a node-sqlite3 query beyond the scope of db.get()?

I'm attempting to validate whether the sha256 hash stored in my sqlite database corresponds with the sha256 hash of the password that the user transmitted to my NodeJS server. The Auth() method is meant to deliver either a true or false result. Is the ...

`Is it possible to remove an empty frame using javascript?`

I have this script that generates a "layer" resembling a frame and I need to remove it. Here is the code for creating the layer: function disableLayer() { var layer = document.getElementsByTagName('div')[0]; d = document.createElement(& ...

What are the methods for choosing various boxes using the UP/DOWN/RIGHT/LEFT arrow keys?

This code snippet displays a 3x3 matrix where boxes can be hovered over and selected. The goal is to navigate around with keys and select boxes using ENTER. Can anyone provide guidance on how to achieve this functionality? <link rel="stylesheet" href ...

Using the .map method to index an array is causing issues in Node.js

Hey everyone, I'm struggling to properly index a JSON array using the map function. It seems like my code isn't quite right. This is what I have: var entireHTMLssssq = lloopmois.map((result, index) => `<div id=${index} style="position: a ...

Exploring the Fusion of Strings and Arrays of Javascript Objects using jQuery and JSON

Trying to achieve a simple task, but not very proficient in jQuery so struggling to figure it out. Want to send JSON data to an ASP.NET Controller. Data includes strings and a list of objects. The code snippet would appear like this: View: $(document). ...