Hold off until the commitments have been fulfilled before determining if they are true or false

I need assistance with waiting for a promise to return within a method.

public async loginOffline(username: string, password: string) {
    const data = await this.database.getItem('currentUser', 'login');
    this.userLogin = data;
    console.log(`${username} ${this.userLogin.username} ${password} ${this.userLogin.password}`);
    if (username === this.userLogin.username && password === this.userLogin.password) {
        return true;
    } else {
        return false;
    }
}

/********* Calling the method and deciding what to do **************/
if (await loginOffline('myname', 'mypassword')) {
    // Do something.....
} else {
    // Do something else .....
}
......

The current implementation is not functioning as expected. The caller of the loginOffline method only needs confirmation on whether the login was successful. I have attempted multiple approaches but none have worked so far.

If anyone can provide some guidance, it would be greatly appreciated. Thank you very much.

Answer №1

To continue the promise chain, simply use another then method. Implement it like this:

loginOffline('myname', 'mypassword').then(result =>{
   if(result){
     //perform a specific action
   }else{
     //perform a different action
   }
})

For additional information on promise chaining

Answer №2

Here is an example of using the Promise object:

function checkCredentials(username: string, password: string) {
  return database.fetchUser('currentUser').then(userData => {
      let user = userData;
      console.log(username + ' ' + user.username + ' ' + password + ' ' + user.password );
      if (username === user.username && password === user.password) {
        return true;
      } else {
        return false;
      }
    }).catch(err => {
      return false;
    });   
}

checkCredentials('myname', 'mypassword').then((result) => {
    if(result) {
      // Credentials are correct
    } else {
      // Incorrect credentials
    }
 })

Answer №3

Suraj's response provides the correct solution - simply wrap another .then() around the returned result. Alternatively, you can utilize the await/async keywords to refactor the code.

 public async loginOffline(username: string, password: string) {
    try {
      this.userLogin = await this.database.getItem('currentUser', 'login');
    } catch(e) {
      return false;
    }
    console.log(username + ' ' + this.userLogin.username + ' ' + password + ' ' + this.userLogin.password );
    return (
      username === this.userLogin.username &&
      password === this.userLogin.password);
  }

// This code must also be inside a function marked as 'async':
/********* call the method and descide what to do **************/
if(await loginOffline('myname', 'mypassword'){
// Do something.....
} else {
// Do something else .....
}
......

It is important to note that every async function will automatically convert its return value into a Promise, requiring async to be used throughout the entire call stack. If making the caller async is not an option, you can still use then on the result:

// If the caller cannot be marked `async`:
/********* call the method and descide what to do **************/
loginOffline('myname', 'mypassword').then(result => {
  if (result) {
  // Do something.....
  } else {
  // Do something else .....
  }
});
......

Answer №4

For the solution, please refer to the code snippet below:

const checkUserPermission = () => {
  return new Promise((resolve, reject) => {
    fetchData().then((data) => {
      if (data) {
        resolve(true);
      } else {
        resolve(false);
      }
    }).catch((error) => {
      resolve(false);
    })
  })
}

function fetchData() {
  return new Promise((resolve, reject) => { 
    setTimeout(() => {
      resolve("Data");
    }, 100)
  })
}

checkUserPermission().then((data) => {
  alert(data);
});

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

Tips for Sending Specific Row Information to Server in Ionic 3

Successfully pulled contacts from the device into my list page, but struggling to send specific contact details (name and number) to the server. Can anyone provide guidance on accomplishing this in Ionic? ...

Tips for including a currency symbol before an input field using Material UI

Trying to add a dollar sign to the left of an input field using InputAdornment but it's not displaying correctly. Check out my code here: https://codesandbox.io/s/material-demo-wnei9?file=/demo.js ...

Create a reusable React widget in a JavaScript file and integrate it into an ASP.NET MVC project

Is there a way to create a widget with the React library and compile it into a single JavaScript file for reuse in any non-React application (particularly in ASP .NET)? ...

Error: Attempting to access properties of an undefined value (reading '0') within the Array.map function

Take a look at this image illustrating the issue I'm facing export const FlipData = [ { id: "1", tittle: "IT Manpower Consultant", points: [ "Devops and IT consulting", "Renting Servers&quo ...

Visualization with D3 - Putting an image at the heart of a circular chart made with SVG

Is it possible to add an image to the center of a donut SVG in D3 charts using JavaScript? I've been attempting to achieve this but haven't had any success so far. Currently, I have inserted the image in HTML, but it does not align with the cent ...

Adjust the button's background color once it is clicked

Hello, I have been working on a rating button and I am trying to change the background color of the button after it is clicked. However, my code seems to be ineffective in achieving this goal. <ul> <li><button class="btn& ...

Tips for creating gaps between list items in a collapsible navbar

I am attempting to add spacing between the li items in my collapsible navbar However, the issue arises when I slightly minimize the browser window, causing the navbar to collapse incorrectly. See image below: https://i.sstatic.net/TdKb4.png Below is t ...

Is there a way to find out the ultimate destination of a shortened URL without actually opening the webpage?

I am trying to implement a feature where I can click on links within email messages and have the full link displayed in a separate pane using jQuery. However, I am facing some challenges with this implementation. My plan is to use AJAX to call a PHP scrip ...

Retrieve data from an array of objects nested within another object

Imagine a scenario where there is an object containing an array of objects. let events = { "id": 241, "name": "Rock Party", "type": "party", "days": [ { "i ...

Trigger a Tabulator event when a checkbox is selected in Vue 3

Currently, I am utilizing Vue3 along with Tabulator (5.2.7) to create a data table using the Composition API. In the following code snippets, I have excluded irrelevant parts of the code. //DataTable.vue <script setup> import { TabulatorFull as Tabu ...

javascript monitoring numerous socket channels for echoes

Currently, I am in the process of developing a chat application. On the server side, I am utilizing: php, laravel 5.4, and pusher. On the client side, I have incorporated vue.js along with laravel-echo. Initially, I successfully created a "public chat roo ...

The primary text is getting truncated when an ion-note is placed inside an ion-list

I'm currently working with Ionic 3 and attempting to create a list of events where the event name appears on the left and the event note (start time) appears on the right using an ion-note. Below is the code snippet: <ion-list *ngIf="events.len ...

Different ways to activate the system bell in Node.js

Currently, I have a custom nodejs script running for an extended period and I'm seeking a way to receive a notification once the script finishes its execution. Is there a method in nodejs that can be used to activate the "System Bell" alert? ...

Whoops! Unable to interpret properties from an undefined source while trying to retrieve 'get'

Every time I execute my program, I encounter the following error: Cannot read properties of undefined (reading 'get') TypeError: Cannot read properties of undefined (reading 'get') at Proxy.mounted (webpack-internal:///./node_module ...

Using TypeScript to ensure the correct typing for the return type of AsyncThunk when utilizing the 'unwrapResult' method from Redux Toolkit

Struggling to determine the appropriate return type for an AsyncThunkAction in order to utilize it with the unwrapResult method from Redux Toolkit (refer to: Redux Tookit: Unwrapping Result Actions): Here is how the Async thunk is declared in the Slice: e ...

Is it necessary to replace Tomcat with Node.js?

I'm exploring building a server with node.js and wondering if I need tomcat as well. I'm new to this, so any insight on these basic concepts would be greatly appreciated. Thank you in advance! ...

Verify in TypeScript whether a property of an object is a function with a specified signature

I am facing an issue with a function that retrieves a property from an object. // Utils.ts export function getProperty<T, K extends keyof T>(obj: T, key: string): T[K] { if (key in obj) { return obj[key as K]; } throw new Error(`Invalid obje ...

What is the best way to determine if an object is empty?

I have an array object that I need to check for emptiness. const sampleData = { test:[], test2:[], test1:["can"] } This is the code I'm using to check for emptiness: const dataObject = Object.values(sampleData) console.log(d ...

Issue with forkJoin in the share component (and merging boolean variables) is not defined

I am facing an issue with my service where I need to share the result of a forkjoin, but the component is showing up as undefined Here is my service logic layer: @Injectable({ providedIn: 'root' }) ...

Issue: Query is not re-executing after navigatingDescription: The query is

On my screen, I have implemented a query as follows: export const AllFriends: React.FunctionComponent = () => { const navigation = useNavigation(); const { data, error } = useGetMyProfileQuery({ onCompleted: () => { console.log('h ...