Sco*_*ttt 7 javascript promise reactjs request-promise
所以我创建了一个组件,它使用我提供的 props 发送 post 请求。
尽管我熟悉 Async await 我出于某种原因似乎无法让它返回已履行的承诺的实际值,而只是挂起。
我尝试使用更多功能进行包装,因为我知道承诺没有得到解决。
我觉得我错过了一些东西。
下面是我的代码示例
export default class PostController extends React.Component {
constructor(props) {
super(props)
}
Wrapper = (body) => {
try{
let x = this.Send(body);
return x;
console.log(x)
}catch(e){console.log(e)}
}
Send = async (body) => {
try{
let data = await this.Post(body);
return data;
}catch(e){console.warn(e)}
}
Post = async (body) => {
try{
const options = {
method: 'POST',
uri: 'XXXXXXXXXXXXXXXXXXXX',
body: body
}
const data = await rp(options);
return data;
}catch(e){console.warn(e)}
}
render(props) {
let jsonBody = JSON.stringify(this.props.data)
const returnData = this.Wrapper(jsonBody)
console.log(returnData)
return(
<div>
{(!this.props.data.pw) ? 'Retrieved Password: ' + returnData.message : 'Generated PassWord!:' + returnData.message }
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
}
Tan*_*Dat 11
我认为你需要更多关于async/awaitJS 的内容。
Anasync function总是回报一个承诺。所以x这Wrapper是一个承诺。因为你不使用await/async.
应该是这样的。
async Wrapper = (body) => {
try{
let x = await this.Send(body); // <-- missing await here
return x;
}catch(e){console.log(e)}
}
Run Code Online (Sandbox Code Playgroud)
但随后,里面的代码render就不起作用了。因为this.Wrapper()现在返回了一个承诺。-> returnData is a promise。并且该render方法不能是异步函数:)
render(props) {
//...
const returnData = this.Wrapper(jsonBody) // <-- returnData here is a promise.
//...
Run Code Online (Sandbox Code Playgroud)
所以要让事情顺利进行。
你必须使用state. 调用this.WrapperincomponentDidMount或componentDidUpdate. 例如:
constructor() {
// ...
this.state = { returnData: null }
}
async componentDidMount() {
const returnData = await this.Post(...); // Using await to get the result of async func
this.setState({ returnData });
}
async Post(body) {
try{
const options = {
method: 'POST',
uri: 'XXXXXXXXXXXXXXXXXXXX',
body: body
}
return rp(options); // define await then return is unnecessary
}catch(e){console.warn(e)}
}
render() {
const { returnData } = this.state;
// ... Do the rest
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16798 次 |
| 最近记录: |