Need to chain API call such that the data returned in the first API call Promise is then used call another API call. The Api calls return Json data where a field in array format is then used where each of those array call another API call and this goes on to multiple level and a few API calls. I understand nesting the API calls would be a poor practice and better to use async and await or chain the promises? but in the situation that the data returned has an array which I then want to carry forward to make another API call for each element in that array which each will result in multiple promises with array data which again needs to make an API call on each and so forth.
Asked
Active
Viewed 386 times
-1
-
share your code what you have try so far ,... – Taylor Rahul Jan 13 '21 at 05:45
-
1This sounds like a job for Promise.all(). Have you looked into that? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all – James Hamann Jan 13 '21 at 05:48
-
Please make your question clearer and share what you have tried till now – sonali Jan 13 '21 at 05:50
-
Perhaps this is what you want: [How to chain and share prior results with promises](https://stackoverflow.com/questions/28714298/how-to-chain-and-share-prior-results-with-promises/28714863#28714863). – jfriend00 Jan 13 '21 at 05:51
-
@TaylorRahul Adding the code below where i have nested but i want to rewriter it efficiently. client.workspaces.getWorkspaces({ opt_pretty: true }).then((wrkspaces) => {wrkspaces.data.map((wrkspace) =>client.projects.getProjects({ workspace: rkspace.gid, opt_pretty: true }).then((Projects) => {console.log(Projects); Projects.data.map((Project) =>client.tasks .getTasksForProject(Project.gid, { opt_pretty: true }).then((tasks) => { tasks.data.map((task) => {client.tasks.getTask(task.gid, { opt_pretty: true }).then((taskdetails) => { .... – Caryappa B C Jan 13 '21 at 07:28
1 Answers
0
Create a promise for each API call and use Promise.all something like
let urls = [
'https://api.com/product/1',
'https://api.com/product/2',
'https://api.com/product/3',
];
// map every url to the promise of the fetch
let requests = urls.map(url => fetch(url));
// Promise.all waits until all jobs are resolved
Promise.all(requests)
.then(responses => responses.forEach(
response => alert(`${response.url}: ${response.status}`)
));

sonali
- 762
- 10
- 23