Im trying to iterate over an suites array that returned from http call then on each iteration have to call api to get points against each suite. Each call returned a promise and i have to construct an array and populate result from each api call response. I would like to return result array once everything within the suites.forEach loop is all done. But the current code retrun control after 1st suites.forEach occurance.
import Q = require("q");
public static getTestResults(testcaseId: number): Promise<TestResult[]>{
let deferredPromise = Q.defer<TestResult[]>();
let results: TestResult[] = [];
let testManagementRestClient: TestManagementRestClient.TestHttpClient4_1;
testManagementRestClient = TestManagementRestClient.getClient();
testManagementRestClient.getSuitesByTestCaseId(testcaseId).then(suites => {
suites.forEach(suite => {
testManagementRestClient.getPoints(suite.project.id, suite.plan.id,
suite.id, undefined, undefined,
testcaseId.toString(), undefined,
true, undefined, undefined
).then(points => {
points.forEach(point => {
results.push(
{
projectId: suite.project.id,
runId: point.lastTestRun.id,
configuration: point.configuration.name
}
);
});
deferredPromise.resolve(results);
});
});
});
return deferredPromise.promise;
}
I googled and find out the $q.all() but didn't know how i can implement this on this specific scenario and if it resolve my issue.
Any advices would be welcomed! Thanks!
CodePudding user response:
I think what you are looking for here is Promise.all
. Assemble the calls to your rest endpoint as an array of tasks, something along the lines of:
const tasks = suites.map(suite => testManagementRestClient.getPoints(...
And then to wait for all those tasks to resolve, use Promise.all
as follows:
await Promise.all(tasks);
You can find more about Promise.all
here
CodePudding user response:
Solution from @Marcus is working fine. Here is another way to handle wait for all.
public static getTestResults(testcaseId: number): Promise<TestPoints[]> {
let deferredPromise = Q.defer<TestPoints[]>();
let results: TestPoints[] = [];
let testManagementRestClient: TestManagementRestClient.TestHttpClient4_1;
testManagementRestClient = TestManagementRestClient.getClient();
testManagementRestClient.getSuitesByTestCaseId(testcaseId).then(async suites => {
for (const suite of suites) {
const points = await testManagementRestClient.getPoints(
suite.project.id,
suite.plan.id,
suite.id,
undefined,
undefined,
testcaseId.toString(),
undefined,
true,
undefined,
undefined
);
points.forEach(point => {
results.push(
{
projectId: suite.project.id,
runId: point.lastTestRun.id,
configuration: point.configuration.name " (" suite.name ")"
}
);
});
}
deferredPromise.resolve(results);
});
return deferredPromise.promise;
}