0

In Reactjs, I need to turn the below try catch function into promise function:

  function one(){
      try{
       const response = await AA.sendMsg({XX})
       if(response){
           setState({response})
         }
       }catch(e){
        console.log(e)
        }
    }

My coding is like this:

const one = new Promise((resolve,reject))=> {
    AA.sendMsg({XX})
  .then(response => setState({response}) )
  .catch(e => {console.log(e)})
}

But it does not work. Anyone can tell me the right way to do it?

leafend617
  • 183
  • 1
  • 2
  • 8
  • why? have you considered using babel or something to keep it async-await? – Daniel A. White Sep 08 '20 at 00:41
  • 2
    They’re both promise based. In the second example, the wrapped promise is kinda pointless as you already have a promise. – evolutionxbox Sep 08 '20 at 00:42
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it) and don't do that! – Bergi Sep 08 '20 at 00:58

1 Answers1

2

Its not working because you're assigning a new Promise to one instead of what you really want to do which is this:

function one() {
    // AA.sendMessage is already a promise.
    return AA.sendMessage({})
        .then(response => console.log("Got a response!", response))
        .catch(error => console.log("Got an error!", error))
}
emeraldsanto
  • 4,330
  • 1
  • 12
  • 25
  • Thanks so much, but how to setState({response}) in this way? Right now my code shows the response is"object of type unknown" – leafend617 Sep 08 '20 at 00:57
  • You replace the `console.log` call with `this.setState({ response })` if using class component or simply `setState({ response })` if using a function component. – emeraldsanto Sep 08 '20 at 00:59