I'm starting and one of the first things I'm trying on my own is how to add multiple sources to this promise:
const getTodos = async () =>{
const response = await fetch('todos/resource.json');
if(response.status !== 200){
throw new Error('Cannot fetch data');
}
const data = await response.json();
return data;
};
getTodos()
.then(data => console.log ('Resolved: ', data))
.catch(err => console.log ('Rejected', err.message);
I tried making different variables and using .then after to print them but that didn't work.
const getTodos = async () =>{
const response = await fetch('todos/resource1.json');
if(response.status !== 200){
throw new Error('Cannot fetch data'); // Error from the source
}
const data = await response.json();
return data;
const response2 = await fetch('todos/resource2.json');
if(response2.status !== 200){
throw new Error('Cannot fetch data'); // Error from the source
}
const data2 = await response2.json();
return data2;
};
getTodos()
.then(data => console.log ('Resolved: ', data))
.then(data2 => console.log ('Resolved: ', data2))
.catch(err => console.log ('Rejected', err.message)) // Error for json file
;
any tips?
CodePudding user response:
If you want to return multiple things from a function, then you either need to return an array or an object. Two return statements will not work. As soon as the first return is hit, you're done. The only difference in an async function is that your single return statement determines the resolution value of the promise. You're still limited to one return though.
So here's an example which returns an object:
const getTodos = async () =>{
const response = await fetch('todos/resource1.json');
if(response.status !== 200){
throw new Error('Cannot fetch data'); // Error from the source
}
const data = await response.json();
const response2 = await fetch('todos/resource2.json');
if(response2.status !== 200){
throw new Error('Cannot fetch data'); // Error from the source
}
const data2 = await response2.json();
return {
data1,
data2,
}
};
// used like:
getTodos().then(result => {
console.log(result.data1);
console.log(result.data2);
});
// or with async/await:
async someFunction () {
const result = await getTodos();
console.log(result.data1);
console.log(result.data2);
}
CodePudding user response:
async function fetchTodoItems(resourceList) {
return Promise.all(
resourceList
.map(url =>
fetch(url).then(response => response.json())
)
);
}
(async () => {
const todoItems = await fetchTodoItems([
'https://jsonplaceholder.typicode.com/todos/1',
'https://jsonplaceholder.typicode.com/todos/11',
'https://jsonplaceholder.typicode.com/todos/21',
'https://jsonplaceholder.typicode.com/todos/31',
'https://jsonplaceholder.typicode.com/todos/41',
'https://jsonplaceholder.typicode.com/todos/51',
'https://jsonplaceholder.typicode.com/todos/61',
]);
console.log({ todoItems });
})();
.as-console-wrapper { min-height: 100%!important; top: 0; }