gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:28:08 25 4
gpt4 key购买 nike

我有一个调用递归异步方法的生命周期方法 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);
}

关于javascript - 如何解决异步函数中的 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53240675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com