ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

javascript-如何解决异步函数中的承诺?

2019-11-08 11:33:34  阅读:178  来源: 互联网

标签:reactjs async-await es6-promise javascript


我有一个生命周期方法componentDidMount,它调用一个递归异步方法,并且我希望递归函数在获取所有数据后返回一个Promise.

  async componentDidMount() {
    let response = await fetch(`${STORY_URL}${this.props.match.params.id}.json`);
    let result = await response.json();

    totalComments = result.descendants;

    await this.fetchComments(result.kids, MARGIN);

    this.setState({
      by: result.by,
      time: calculateTimeDifference(result.time)
    });
  }

而被调用的函数是

async fetchComments(comment, margin) {
    return new Promise((resolve, reject) => {

      comment.map(async commentId => {
        let response = await fetch(`${STORY_URL}${commentId}.json`);
        let result = await response.json();
        comments.push({
          by: result.by,
          margin: margin
        });

        if (comments.length === totalComments + 1)  resolve();

        if (result.kids !== undefined) this.fetchComments(result.kids, margin * 2);
      });
    });
  }

但是resolve方法不会在setState之前返回至componentDidMount.我通过控制台日志检查.我不知道我在做什么错

解决方法:

您使事情变得过于复杂.使用Promise.all:

 async fetchComments(comments, margin) {
   // Collect all the results here, otgerwise we would have to flatMap the promises which is more complicated
   const result = [];

   // Make sure that all comments were processed before returning
   await Promise.all( comments.map(async commentId => {
    const response = await fetch(`${STORY_URL}${commentId}.json`);
    const { kids, by } = await response.json();

    if(kids) {
       // Get all children and append them to the results, right after the children
       const children = await fetchComments(kids, margin * 2);
       result.push({ by, margin }, ...children);
    } else {
       // Otherwise just append this node
      result.push({ by, margin });    
    }   
  }));

  return result;
}

如果顺序很重要,则必须拼合Promise.all的结果:

  async fetchComments(comments, margin) {
    const result = await Promise.all(comments.map( async commentID => {
      const response = await fetch(STORY_URL + commentID + ".json");
      const { by, kids } = await response.json();

      const result = [{ by, margin }];
      if(kids) result.push(... await fetchComments(kids, margin * 2));

      return result;
   }));

   // Flatten the results
   return [].concat(...result);
 }

标签:reactjs,async-await,es6-promise,javascript
来源: https://codeday.me/bug/20191108/2007894.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有