【发布时间】:2019-10-02 19:46:25
【问题描述】:
Async/await 在异步获取数据时派上了用场,尤其是在
async componentDidMount() {
try {
const response = await axios.get(endpoints.one)
const data = await response
this.setState({ data, isLoading: false })
} catch (e) {
this.setState({ errors: e.response })
}
}
此外,当从多个端点获取时,可以轻松使用
Promise.all([
fetch(endpoints.one),
fetch(endpoints.two),
]).then(([data1, data2]) => {
console.log(data1, data2)
}).catch((err) => {
console.log(err);
});
但是,如何使用 aync/await 而不是 Promise.all 从多个来源获取数据?
【问题讨论】:
-
你可以等待
Promise.all()。见this question -
这里的一些答案提供了没有
Promise.all的解决方案:stackoverflow.com/questions/35612428/… -
你可以简单地等待 Promise.all()
标签: javascript reactjs async-await