Javascript 如何将try-catch函数转换为promise函数
在Reactjs中,我需要将下面的try-catch函数转换为promise函数:Javascript 如何将try-catch函数转换为promise函数,javascript,reactjs,Javascript,Reactjs,在Reactjs中,我需要将下面的try-catch函数转换为promise函数: function one(){ try{ const response = await AA.sendMsg({XX}) if(response){ setState({response}) } }catch(e){ console.log(e) } } 我的编码如下: co
function one(){
try{
const response = await AA.sendMsg({XX})
if(response){
setState({response})
}
}catch(e){
console.log(e)
}
}
我的编码如下:
const one = new Promise((resolve,reject))=> {
AA.sendMsg({XX})
.then(response => setState({response}) )
.catch(e => {console.log(e)})
}
但它不起作用。任何人都可以告诉我正确的方法吗?它不起作用,因为你给
一个分配了一个新的承诺,而不是你真正想做的事情,这是:
函数一(){
//AA.sendMessage已经是一个承诺。
返回AA.sendMessage({})
.then(response=>console.log(“得到响应!”,响应))
.catch(error=>console.log(“出现错误!”,error))
}
它不起作用,因为您将一个新的承诺
分配给一个
,而不是您真正想要做的事情,这是:
函数一(){
//AA.sendMessage已经是一个承诺。
返回AA.sendMessage({})
.then(response=>console.log(“得到响应!”,响应))
.catch(error=>console.log(“出现错误!”,error))
}
为什么?您是否考虑过使用babel或其他东西来保持异步等待?它们都是基于承诺的。在第二个例子中,包装好的承诺是没有意义的,因为你已经有了一个承诺。避免使用包装,不要这样做!为什么?您是否考虑过使用babel或其他东西来保持异步等待?它们都是基于承诺的。在第二个例子中,包装好的承诺是没有意义的,因为你已经有了一个承诺。避免使用包装,不要这样做!非常感谢,但是如何以这种方式设置状态({response})?现在,我的代码显示响应是“类型未知的对象”。如果使用类组件,您可以将console.log
调用替换为this.setState({response})
,如果使用函数组件,则简单地替换为setState({response})
。非常感谢,但是如何以这种方式设置状态({response})?现在,我的代码显示响应为“类型未知的对象”。如果使用类组件,则将console.log
调用替换为this.setState({response})
,如果使用函数组件,则替换为setState({response})
。