Here's one way you could go about this using Promise.all:
const fetchExternalData = () => {
return Promise.all([
fetch("file1.txt"),
fetch("file2.txt")
])
.then(
results => Promise.all(
results.map(result => result.text())
)
)
}
Then, when calling your fetchExternalData function, you will get an array of items with data from both of your files:
fetchExternalData().then(
(response) => {
// [file1data, file2data]
}
)
Here's an example:
const fetchExternalData = () => {
return Promise.all([
fetch("https://jsonplaceholder.typicode.com/todos/1"),
fetch("https://jsonplaceholder.typicode.com/todos/2")
]).then(results => {
return Promise.all(results.map(result => result.json()));
});
};
fetchExternalData()
.then(result => {
// console.log(result);
})
.catch(console.error);
Alternatively, if you'd want to return an object instead of an array, you could do something like the following:
const fetchExternalData = items => {
return Promise.all(
items.map(item =>
fetch(`https://jsonplaceholder.typicode.com/todos/${item.id}`)
)
)
.then(
responses => Promise.all(
responses.map(response => response.json())
)
)
// use `Array.reduce` to map your responses to appropriate keys
.then(results =>
results.reduce((acc, result, idx) => {
const key = items[idx].key;
// use destructing assignment to add
// a new key/value pair to the final object
return {
...acc,
[key]: result
};
}, {})
);
};
fetchExternalData([
{ id: 1, key: "todo1" },
{ id: 2, key: "todo2" }
])
.then(result => {
console.log("result", result);
console.log('todo1', result["todo1"]);
})
.catch(console.error);
References:
return [resp1.text() , resp2.text()]then usePromise.all()to wait on them