Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/438.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何解析异步函数中的承诺?_Javascript_Reactjs_Async Await_Es6 Promise - Fatal编程技术网

Javascript 如何解析异步函数中的承诺?

Javascript 如何解析异步函数中的承诺?,javascript,reactjs,async-await,es6-promise,Javascript,Reactjs,Async Await,Es6 Promise,我有一个生命周期方法componentDidMount,它调用递归异步方法,我希望递归函数在获取所有数据后返回一个承诺 async componentDidMount() { let response = await fetch(`${STORY_URL}${this.props.match.params.id}.json`); let result = await response.json(); totalComments = result.descendant

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

  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。我通过控制台日志检查。我不知道我做错了什么

你把事情搞得太复杂了。使用
承诺。所有

 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;
}
  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);
 }
如果顺序很重要,您必须将
承诺的结果展平。所有

 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;
}
  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);
 }

fetch
返回承诺。因此,您可能不需要将fetch放在promise中。我如何解析使用该promise来解析wait?此函数的目标是将所有数据推送到一个数组中。这可以完成任务吗?@puskar现在可以:)这不需要将内容按与
注释相同的顺序推入
结果
数组,如果有必要的话。是的,我还需要按与获取数据相同的顺序推送数据。我以前尝试过一个不同的实现,它有相同的功能issue@puskar是的,这是可能的,但它稍微复杂一点。