在我的应用程序中,我构建了一系列对第 3 方 API 的调用,每个调用都返回一个承诺,然后使用
Promise.All
在结果全部解决后对结果采取行动。
我发现自己重复了一种使用这种方法的模式,但还需要为每个条目存储额外的元数据。例如,如果它是文件加载器承诺的数组,我可能想存储每个文件的文件类型、预期目的地等。
目前,我使用此信息构建了另一个数组,并且由于我知道
Promise.All
的结果将按照添加的顺序出现,因此我可以使用适当的索引查找 API 调用的结果和元数据。
我想知道是否可以创建一个数组,其中包含返回 Promise 的 API 调用和作为单个 JavaScript 对象的数据,以便在解析后可以轻松提取两者。
尽管进行了很多尝试,我还是无法找到适合我的语法,但感觉这是可能的。
有人可以帮忙吗?
编写一个自定义函数,可以返回每个 API 调用的承诺数组以及任何聚合信息。
类似于下面的东西可以工作。
async function fetchAPIsAndCompileResults() {
// API endpoints
const apiEndpoint1 = 'https://example.com/api/endpoint1';
const apiEndpoint2 = 'https://example.com/api/endpoint2';
// Function to fetch data from an API
async function fetchData(apiUrl) {
const response = await fetch(apiUrl);
return await response.json();
}
// Execute both API calls concurrently and keep them as promises
const apiCallPromises = [
fetchData(apiEndpoint1),
fetchData(apiEndpoint2),
];
// Aggregate your specific information, from each API call into an array
// Wait for all API call promises to resolve
let aggregatedInfo = [];
const results = (await Promise.all(apiCallPromises)).forEach(result => { // Grab your aggregated info
if (result && result.items) {
aggregatedInfo = [...aggregatedInfo, ...result.items];
}
});
// Finally return an object containing both the promises and the aggregatedInfo
return {
apiCalls: apiCallPromises, // Array of promises for each API call
aggregatedInfo // The aggregated information from all API calls once they resolve
};
}
// Example usage
fetchAPIsAndCompileResults().then(({ apiCalls, aggregatedInfo }) => {
Promise.all(apiCalls).then(() => {
console.log('API Calls Completed');
console.log(aggregatedInfo); // Aggregated information after API calls have resolved
});
});