disp_name
disp_name

Reputation: 1488

Nested Promises: Creating N promises based on array

I have N workspaces. The number N is dynamic.

Every workspace has to execute a few pre-defined queries.

What I am currently doing is looping through an array of workspaces(Synchronously) and executing all the queries using Promise.all() (which is asynchronous).

Goal: What I need is to run all the queries for all the workspaces asynchronously. So I want to get rid of the loop to go thru each workspace. The ideal result would be an array of array. For example, if there are 3 workspaces and 2 queries the result would be [[q1, q2], [q1,q2], [q1,q2]] each q1 and q2 are the results for every workspace.

Below is the sample code:

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]
}

How can I create another promise object to make it async?

Feel free to ask if you need anything else to get more clarity.

Upvotes: 1

Views: 141

Answers (2)

bigLucas
bigLucas

Reputation: 654

you need to use .map() function.

Upvotes: 1

Mosh Feu
Mosh Feu

Reputation: 29239

If I understand you correctly, you can map() that workspaces array into Promises array and wrap it with Promise.all.

The below code is "pseudo" to make the point.

If it not reflects your situation, I'll probably need more information.

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);
})();

Upvotes: 1

Related Questions