我有 N 个工作区。数字 N 是动态的。
每个工作区都必须执行一些预定义的查询。
我当前正在做的是循环遍历工作区数组(同步
)并使用Promise.all()
(这是异步
)。
目标:我需要的是异步运行所有工作区的所有查询。所以我想摆脱遍历每个工作区的循环。理想的结果是数组的数组。例如,如果有 3 个工作区和 2 个查询,结果将是 [[q1, q2], [q1,q2], [q1,q2]]
每个 q1 和 q2 是每个的结果工作区。
下面是示例代码:
async function fetchingWorkspaceLogs (workspaceId) {
// Defining q1QueryString, q2QueryString so on...
// for azure "loganalytics" reader.
const [q1Result, q2Result, q3Result] = await Promise.all([
logAnalyticsReader.query(
q1QueryString,
workspaceId
),
logAnalyticsReader.query(
q2QueryString,
workspaceId
),
])
// return some promises
}
// Parse all workspaces for query
for (let j = 0; j < workspaceIdList.length; j++) {
workspaceId = workspaceIdList[j]
const queryResults = await fetchingWorkspaceLogs(workspaceId)
q1QueryResults = queryResults[0]
q2QueryResults = queryResults[1]
}
如何创建另一个 Promise 对象以使其异步?
如果您还需要任何其他信息来获得更清晰的信息,请随时询问。
最佳答案
如果我理解正确,您可以将工作区数组 map()
映射到 Promises
数组中,并用 Promise.all
包装它。
下面的代码是“伪”代码来说明这一点。
如果它不能反射(reflect)您的情况,我可能需要更多信息。
async function fetchingWorkspaceLogs (workspaceId) {
const [q1Result, q2Result] = await Promise.all([
Promise.resolve(`param1: ${workspaceId}`),
Promise.resolve(`param2: ${workspaceId}`),
]);
// In this example, the function returns the result to make the point of returning Promise with the information
return Promise.resolve([q1Result, q2Result]);
}
const workspaceIdList = ['workspace1', 'workspace2', 'workspace3'];
(async () => {
const result = await Promise.all(
workspaceIdList.map(workspace => fetchingWorkspaceLogs(workspace))
);
console.log(result);
})();
关于javascript - 嵌套 Promise : Creating N promises based on array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60061046/