簡體   English   中英

如何解決異步函數中的promise?

[英]How to resolve a promise in an async function?

我有一個生命周期方法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);
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM