Javascript 承诺后返回值

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

在Promise.all之后如何从renderDirect函数返回值? 这是我的派遣行动:

 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.log
renderDirect
函数,这里是输出:

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的结果