2 回答

TA貢獻1921條經驗 獲得超9個贊
這是您可以使用的一種方法Promise.all:
const fetchExternalData = () => {
return Promise.all([
fetch("file1.txt"),
fetch("file2.txt")
])
.then(
results => Promise.all(
results.map(result => result.text())
)
)
}
然后,在調用您的fetchExternalData函數時,您將獲得一個包含兩個文件中數據的項目數組:
fetchExternalData().then(
(response) => {
// [file1data, file2data]
}
)
這是一個例子:
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);
或者,如果您想返回 anobject而不是 an array,您可以執行以下操作:
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);

TA貢獻1884條經驗 獲得超4個贊
通過將其放入對象中返回多個值。像這樣:
const fetchExternalData = async() => {
const resp1 = await fetch('file1.txt');
const resp2 = await fetch('file2.txt');
return ({res1: resp1.text(), res2: resp2.text()});
}
添加回答
舉報