简体   繁体   English

如何将try catch函数变成promise函数

[英]How to turn try catch function into promise function

In Reactjs, I need to turn the below try catch function into promise function:在 Reactjs 中,我需要将下面的 try catch 函数变成 promise 函数:

  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?任何人都可以告诉我正确的方法吗?

Its not working because you're assigning a new Promise to one instead of what you really want to do which is this:它不工作,因为你分配一个新的Promise ,以one什么,而不是你真正想做的事情是这样的:

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))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM