【发布时间】:2019-04-13 21:44:10
【问题描述】:
我有一个生命周期方法 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。我通过控制台日志检查。我不知道我做错了什么
【问题讨论】:
-
fetch返回一个承诺。所以你可能不需要把 fetch 放在一个 Promise 中 -
我怎样才能解决使用该承诺来解决等待?
标签: javascript reactjs async-await es6-promise