Promise.all 后的返回值

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


 this.props.getChildrens(),

 this.props.getTeachers(),

 this.props.getTeachers()

渲染重定向功能:


renderRedirect = async () => {

   Promise.all([

     this.props.getChildrens(),

     this.props.getTeachers(),

     this.props.getTeachers()

    ]).then(() => {

      return 'test';

    });

  };

在我的组件中,我的 console.logrenderRedirect函数是输出:


console.log(this.renderRedirect())

Promise {<resolved>: undefined}


侃侃无极
浏览 1338回答 2
2回答

qq_笑_17

你忘了回来Promise.all。renderRedirect = () => {&nbsp; &nbsp;// added return keyword&nbsp; &nbsp;return Promise.all([&nbsp; &nbsp; &nbsp;this.props.getChildrens(),&nbsp; &nbsp; &nbsp;this.props.getTeachers(),&nbsp; &nbsp; &nbsp;this.props.getTeachers()&nbsp; &nbsp; ]).then(() => {&nbsp; &nbsp; &nbsp; return 'test';&nbsp; &nbsp; });&nbsp; };但是你也应该注意到console.log(this.renderRedirect())仍然不起作用,因为你需要await为承诺的结果。你应该做这样的事情:let result = await this.renderRedirect()console.log(result)

人到中年有点甜

三个问题:您需要return调用Promise.all的then处理程序的结果,或者使用简洁的函数体,以便隐式返回。如果您要 make&nbsp;renderRedirect&nbsp;async,则使用await.您正在从renderRedirect.&nbsp;您需要使用该承诺,而不是输出它。要处理 #1 和 #2,要么:// Concise arrow function, not `async`renderRedirect = () => Promise.all([&nbsp; &nbsp; &nbsp;this.props.getChildrens(),&nbsp; &nbsp; &nbsp;this.props.getTeachers(),&nbsp; &nbsp; &nbsp;this.props.getTeachers()&nbsp; &nbsp; ]).then(() => {&nbsp; &nbsp; &nbsp; return 'test';&nbsp; &nbsp; });或// `async` functionrenderRedirect = async () => {&nbsp; &nbsp; await Promise.all([&nbsp; &nbsp; &nbsp;this.props.getChildrens(),&nbsp; &nbsp; &nbsp;this.props.getTeachers(),&nbsp; &nbsp; &nbsp;this.props.getTeachers()&nbsp; &nbsp; ]);&nbsp; &nbsp; return 'test';};处理#3:this.renderRedirect().then(result => {&nbsp; &nbsp; console.log(result);});或者如果该代码在async函数中:console.log(await this.renderRedirect());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript