Async/await has e in handy when fetching data asynchronously, especially in the
async ponentDidMount() {
try {
const response = await axios.get(endpoints.one)
const data = await response
this.setState({ data, isLoading: false })
} catch (e) {
this.setState({ errors: e.response })
}
}
Moreover, when fetching from multiple endpoints, one can easily use
Promise.all([
fetch(endpoints.one),
fetch(endpoints.two),
]).then(([data1, data2]) => {
console.log(data1, data2)
}).catch((err) => {
console.log(err);
});
However, how can one use aync/await to fetch data from multiples sources instead of Promise.all?
Async/await has e in handy when fetching data asynchronously, especially in the
async ponentDidMount() {
try {
const response = await axios.get(endpoints.one)
const data = await response
this.setState({ data, isLoading: false })
} catch (e) {
this.setState({ errors: e.response })
}
}
Moreover, when fetching from multiple endpoints, one can easily use
Promise.all([
fetch(endpoints.one),
fetch(endpoints.two),
]).then(([data1, data2]) => {
console.log(data1, data2)
}).catch((err) => {
console.log(err);
});
However, how can one use aync/await to fetch data from multiples sources instead of Promise.all?
Share Improve this question asked May 15, 2019 at 15:43 Erick MwazongaErick Mwazonga 1,3001 gold badge14 silver badges27 bronze badges 3-
You can await
Promise.all()
. See this question – Chris B. Commented May 15, 2019 at 15:45 -
some answers from here provide solutions without
Promise.all
: stackoverflow./questions/35612428/… – Andrey Commented May 15, 2019 at 15:46 - you can simply await Promise.all() – GifCo Commented May 15, 2019 at 15:46
1 Answer
Reset to default 13If you want to do them in parallel, then you'll still Promise.all. Just you'll await
the result rather than calling .then
async someFunction() {
try {
const [data1, data2] = await Promise.all([
fetch(endpoints.one),
fetch(endpoints.two),
]);
console.log(data1, data2);
} catch (err) {
console.log(err);
}
}