Reputation: 73
I need to wait for two fetch()
API calls and then to save data from each fetch to different window object. I found this article https://gomakethings.com/waiting-for-multiple-all-api-responses-to-complete-with-the-vanilla-js-promise.all-method/ and tried following code to wait for the API calls:
Promise.all([
fetch('https://jsonplaceholder.typicode.com/todos/1'),
fetch('https://jsonplaceholder.typicode.com/todos/2')
]).then(function (responses) {
// Get a JSON object from each of the responses
return Promise.all(responses.map(function (response) {
return response.json();
}));
}).then(function (data) {
// Log the data to the console
// You would do something with both sets of data here
console.log(data);
}).catch(function (error) {
// if there's an error, log it
console.log(error);
});
However when pasting this in browser console, the result is not being logged.
What is wrong with the code and how to wait for both to be resolved?
Upvotes: 5
Views: 11103
Reputation: 2655
const fetchData = async () => {
try {
const responsesJSON = await Promise.all([
fetch('https://jsonplaceholder.typicode.com/todos/1'),
fetch('https://jsonplaceholder.typicode.com/todos/2')
]);
const [todoOne, todoTwo] = await Promise.all(responsesJSON.map(r => r.json()));
console.log(todoOne, 'todoOne');
console.log(todoTwo, 'todoTwo');
} catch (err) {
throw err;
}
};
fetchData();
Might be looking for something like this.
Upvotes: 6
Reputation: 2255
My suggestion:
let url = "https://jsonplaceholder.typicode.com/todos/";
async function doRequest() {
let toDo1 = await (await fetch(url + "1")).json();
console.log(toDo1);
let toDo2 = await (await fetch(url + "2")).json();
console.log(toDo2);
}
doRequest()
.catch(err => console.log(err));
This way, if you need to fetch multiple items, you can use a loop inside the function.
Upvotes: 0
Reputation: 2053
You can try this thing. I tested it on a fiddle and it looks like it works.
Promise.all([
fetch("https://jsonplaceholder.typicode.com/todos/1"),
fetch("https://jsonplaceholder.typicode.com/todos/2")
]).then(responses =>
Promise.all(responses.map(response => response.json()))
).then(data =>
console.log(data)
).catch(err =>
console.log(err)
);
Upvotes: 4
Reputation: 73
The problem was on my side. I was accidentally filtering the browser console. However thank you all for your help.
Upvotes: 0
Reputation: 29
please use axios for fetch data in js . react or angular etc...
https://github.com/axios/axios please install with npm and read doc
$ npm install axios
axios.get('/user')
.then(function (response) {
console.log(response);
axios.get('/user') .then(function (res) {
console.log(res);
})
})
when first req is finish, then start req sec
Upvotes: -4