1

I Wish use a promise inside a Class and depend if resolve or reject do another method of class of my component. Here I leave a code.

var promise = new Promise( (resolve, reject) => {

  let name = 'DaveA'

  if (name === 'Dave') {
     resolve("Promise resolved successfully");
  }
  else {
     reject(Error("Promise rejected"));
  }
});

class App extends React.Component
{
  constructor(props){
    super(props);
    this.state = {
      name: '',
    }
   
  }
  Bien(result){
    alert("OK")
    this.setState({name: result});
  }
  Mal(error){
    alert("FALLO")
    this.setState({name: error});
  }
  componentDidMount() {
  
 
    let obj = {newName: ''};
   
    promise.then( result => {
     this.Bien(result)
  
    }, function(error) {
      this.Mal(error)
  
    });

I create a simple promise. The from ComponentDidMount i Call it. And after I call another method. but never calls it. appear an error:

 WARN     Possible Unhandled Promise Rejection (id: 0):
TypeError: this.Mal is not a function. (In 'this.Mal(error)', 'this.Mal' is undefined)
Daniel Rayos
  • 51
  • 1
  • 3

1 Answers1

-1

Please use .catch() as this:

componentDidMount() {
    let obj = {newName: ''};
    promise.then(result => {
     this.Bien(result)
    })
    .catch((error) => {
      this.Mal(error)
    });
  }

So total codes should be as following as:

import React, { Component } from 'react';

var promise = new Promise((resolve, reject) => {
    let name = 'DaveA'
    if (name === 'Dave') {
      resolve("Promise resolved successfully");
    }
    else {
      reject(Error("Promise rejected"));
    }
  });

class App extends React.Component
{
  constructor(props){
    super(props);
    this.state = {
      name: '',
    }
  }

  Bien(result) {
    alert("OK")
    this.setState({name: result});
  }

  Mal(error) {
    alert("FALLO")
    this.setState({name: error});
  }

  componentDidMount() {
    let obj = {newName: ''};
    promise.then(result => {
     this.Bien(result)
    })
    .catch(error => {
      this.Mal(error)
    });
  }

  render() {
    return <></>
  }
}

export default App;

It's working correctly on "react": "16.12.0". The result alerted "FALLO".

NinjaDev
  • 1,228
  • 11
  • 21
  • No, don't use `catch`. [Using `.then(…, …)` is totally fine](https://stackoverflow.com/q/24662289/1048572), especially in the OP's case. – Bergi Feb 24 '21 at 21:02
  • you can't use it without `catch` – NinjaDev Feb 24 '21 at 21:55
  • Of course you can. Notice `catch` is just an alias for another `then` call with the handler as the second argument. – Bergi Feb 24 '21 at 22:15