Reputation: 203
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?
Upvotes: 0
Views: 34
Reputation: 4741
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))
}
Upvotes: 2