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?
Edit1:
I'm essentially trying to translate this
const getTodos = (resource) => {
return new Promise((resolve, reject) =>{
const request = new XMLHttpRequest();
request.addEventListener('readystatechange', () =>{
if(request.readyState === 4 && request.status === 200){
const data = JSON.parse(request.responseText);
resolve(data);
} else if(request.readyState === 4){
reject('Error getting resource');
}
});
request.open('GET', resource);
request.send();
})
}
// Then - To get data successfully, Catch - to catch error
getTodos('todos/food.json').then(data =>{
console.log('Promise resolved', data);
return getTodos('todos/sports.json')
}).then(data =>{
console.log('Promise 2 resolved', data)
return getTodos('todos/games.json')
}).then(data =>{
console.log('Promise 3 resolved', data)
return getTodos('todos/sportss.json') //Error example
}).then(data =>{
console.log('Promise 4 resolved', data)
}).catch(err => {
console.log('Promise Rejected', err)
});
into async await.
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);
}
From the above comment ...
"The OP might have a look into either or both
Promise.allandPromise.allSettled"
async function fetchTodoItems(resourceList) {
return Promise.all(
resourceList
.map(url =>
fetch(url)
.then(response => response.json())
)
);
}
(async () => {
try {
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 });
} catch(exception) {
console.log('failed to fatch data with ...', { exception });
}
})();
.as-console-wrapper { min-height: 100%!important; top: 0; }
Promise.all fails fast and the error/exception handling can be done at one place within the code ...
async function fetchTodoItems(resourceList) {
return Promise.all(
resourceList
.map(url => new Promise((_, reject) => reject('invalid api call'))
// fetch(url)
// .then(response => response.json())
)
);
}
(async () => {
try {
const todoItems = await fetchTodoItems([
'https://jsonplaceholder.typicode.com/todos/1',
]);
console.log({ todoItems });
} catch(exception) {
console.log('failed to fatch data with ...', { exception });
}
})();
.as-console-wrapper { min-height: 100%!important; top: 0; }