Javascript 承诺后返回值
在Promise.all之后如何从renderDirect函数返回值? 这是我的派遣行动:Javascript 承诺后返回值,javascript,reactjs,Javascript,Reactjs,在Promise.all之后如何从renderDirect函数返回值? 这是我的派遣行动: this.props.getChildrens(), this.props.getTeachers(), this.props.getTeachers() RenderDirect函数: renderRedirect = async () => { Promise.all([ this.props.getChildrens(), this.props.getTeac
this.props.getChildrens(),
this.props.getTeachers(),
this.props.getTeachers()
RenderDirect函数:
renderRedirect = async () => {
Promise.all([
this.props.getChildrens(),
this.props.getTeachers(),
this.props.getTeachers()
]).then(() => {
return 'test';
});
};
在我的组件中,我使用console.logrenderDirect
函数,这里是输出:
console.log(this.renderRedirect())
Promise {<resolved>: undefined}
console.log(this.renderDirect())
承诺{:未定义}
您忘了返回承诺。全部
renderRedirect = () => {
// added return keyword
return Promise.all([
this.props.getChildrens(),
this.props.getTeachers(),
this.props.getTeachers()
]).then(() => {
return 'test';
});
};
但是您还应该注意到,console.log(this.renderDirect())
仍然不起作用,因为您需要等待承诺的结果
你应该这样做:
let result = await this.renderRedirect()
console.log(result)
您忘了返回
承诺。全部
renderRedirect = () => {
// added return keyword
return Promise.all([
this.props.getChildrens(),
this.props.getTeachers(),
this.props.getTeachers()
]).then(() => {
return 'test';
});
};
但是您还应该注意到,console.log(this.renderDirect())
仍然不起作用,因为您需要等待承诺的结果
你应该这样做:
let result = await this.renderRedirect()
console.log(result)
三个问题:
您需要返回调用Promise.all
的结果,然后返回处理程序,或者使用简洁的函数体隐式返回
如果要使renderRedirect
async
,则使用wait
更为惯用
您正在从renderDirect
输出承诺。你需要消费这个承诺,而不是输出它
要处理#1和#2,请执行以下任一操作:
// Concise arrow function, not `async`
renderRedirect = () => Promise.all([
this.props.getChildrens(),
this.props.getTeachers(),
this.props.getTeachers()
]).then(() => {
return 'test';
});
或
要处理#3:
或者,如果该代码位于异步
函数中:
console.log(await this.renderRedirect());
三个问题:
您需要返回调用Promise.all
的结果,然后返回处理程序,或者使用简洁的函数体隐式返回
如果要使renderRedirect
async
,则使用wait
更为惯用
您正在从renderDirect
输出承诺。你需要消费这个承诺,而不是输出它
要处理#1和#2,请执行以下任一操作:
// Concise arrow function, not `async`
renderRedirect = () => Promise.all([
this.props.getChildrens(),
this.props.getTeachers(),
this.props.getTeachers()
]).then(() => {
return 'test';
});
或
要处理#3:
或者,如果该代码位于异步
函数中:
console.log(await this.renderRedirect());
现在my console.log output Promise{}@PawełBaca只需检查编辑,您需要等待console.log
it现在my console.log output Promise{}@PawełBaca只需检查编辑,您需要等待console.log
it的结果