How to properly do an asynchronous call in a for loop?Using async/await with a forEach loopHow do I debug Node.js applications?How do I get started with Node.jsHow do I pass command line arguments to a Node.js program?How to decide when to use Node.js?How to exit in Node.jsWhat is the purpose of Node.js module.exports and how do you use it?How to call asynchronous method from synchronous method in C#?How do I update each dependency in package.json to the latest version?What is the difference between asynchronous programming and multithreading?Using async/await with a forEach loop

Have I saved too much for retirement so far?

Is possible to search in vim history?

Can I Retrieve Email Addresses from BCC?

How can "mimic phobia" be cured or prevented?

Query about absorption line spectra

Proof of Lemma: Every nonzero integer can be written as a product of primes

Could the E-bike drivetrain wear down till needing replacement after 400 km?

Global amount of publications over time

Greco-Roman egalitarianism

Why does Async/Await work properly when the loop is inside the async function and not the other way around?

Is it possible to use .desktop files to open local pdf files on specific pages with a browser?

Why has "pence" been used in this sentence, not "pences"?

How do I implement a file system driver driver in Linux?

Journal losing indexing services

What does this horizontal bar at the first measure mean?

Is a model fitted to data or is data fitted to a model?

How can Trident be so inexpensive? Will it orbit Triton or just do a (slow) flyby?

What does the Rambam mean when he says that the planets have souls?

Java - What do constructor type arguments mean when placed *before* the type?

Did US corporations pay demonstrators in the German demonstrations against article 13?

Drawing ramified coverings with tikz

Longest common substring in linear time

A Permanent Norse Presence in America

Fly on a jet pack vs fly with a jet pack?



How to properly do an asynchronous call in a for loop?


Using async/await with a forEach loopHow do I debug Node.js applications?How do I get started with Node.jsHow do I pass command line arguments to a Node.js program?How to decide when to use Node.js?How to exit in Node.jsWhat is the purpose of Node.js module.exports and how do you use it?How to call asynchronous method from synchronous method in C#?How do I update each dependency in package.json to the latest version?What is the difference between asynchronous programming and multithreading?Using async/await with a forEach loop













1















can someone please suggest a proper way on how I can do asynchronous call simultaneously with the values I extracted from an array?



Currently, I have the below implementation but it looks like a blocking code because of the await which basically waits for the result of the API call before it proceeds with the next iteration.



Your suggestions would be much appreciated. Thanks in advance! :)



async function getDetailsById()
let idArr = ['1000', '1001', '1002', '1003'];
let detailsArray = [];
for(let i = 0; i < idArr.length; i++)
let id = idArr[i];
let details = await callSomeApi(id);
detailsArray.push(details);

return detailsArray;










share|improve this question

















  • 4





    Possible duplicate of Using async/await with a forEach loop

    – Liam
    Mar 7 at 9:04











  • I'd agree with Liam. This is a duplicate and the link he's provided is a good one around using promises. It might be worth stepping away from your actual problem and look at async, promises and promise.all before returning to your problem.

    – Chris Adams
    Mar 7 at 9:10






  • 1





    Basically, if you just want to run all the async requests in parallel and then await them all, you could do something like this: return await Promise.all(idArr.map(id => callSomeApi(id)))

    – noseratio
    Mar 7 at 9:16







  • 1





    @noseratio, your simple solution worked for me! Thank you very much! :)

    – jrmtmys
    Mar 15 at 6:16















1















can someone please suggest a proper way on how I can do asynchronous call simultaneously with the values I extracted from an array?



Currently, I have the below implementation but it looks like a blocking code because of the await which basically waits for the result of the API call before it proceeds with the next iteration.



Your suggestions would be much appreciated. Thanks in advance! :)



async function getDetailsById()
let idArr = ['1000', '1001', '1002', '1003'];
let detailsArray = [];
for(let i = 0; i < idArr.length; i++)
let id = idArr[i];
let details = await callSomeApi(id);
detailsArray.push(details);

return detailsArray;










share|improve this question

















  • 4





    Possible duplicate of Using async/await with a forEach loop

    – Liam
    Mar 7 at 9:04











  • I'd agree with Liam. This is a duplicate and the link he's provided is a good one around using promises. It might be worth stepping away from your actual problem and look at async, promises and promise.all before returning to your problem.

    – Chris Adams
    Mar 7 at 9:10






  • 1





    Basically, if you just want to run all the async requests in parallel and then await them all, you could do something like this: return await Promise.all(idArr.map(id => callSomeApi(id)))

    – noseratio
    Mar 7 at 9:16







  • 1





    @noseratio, your simple solution worked for me! Thank you very much! :)

    – jrmtmys
    Mar 15 at 6:16













1












1








1








can someone please suggest a proper way on how I can do asynchronous call simultaneously with the values I extracted from an array?



Currently, I have the below implementation but it looks like a blocking code because of the await which basically waits for the result of the API call before it proceeds with the next iteration.



Your suggestions would be much appreciated. Thanks in advance! :)



async function getDetailsById()
let idArr = ['1000', '1001', '1002', '1003'];
let detailsArray = [];
for(let i = 0; i < idArr.length; i++)
let id = idArr[i];
let details = await callSomeApi(id);
detailsArray.push(details);

return detailsArray;










share|improve this question














can someone please suggest a proper way on how I can do asynchronous call simultaneously with the values I extracted from an array?



Currently, I have the below implementation but it looks like a blocking code because of the await which basically waits for the result of the API call before it proceeds with the next iteration.



Your suggestions would be much appreciated. Thanks in advance! :)



async function getDetailsById()
let idArr = ['1000', '1001', '1002', '1003'];
let detailsArray = [];
for(let i = 0; i < idArr.length; i++)
let id = idArr[i];
let details = await callSomeApi(id);
detailsArray.push(details);

return detailsArray;







node.js async-await






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 7 at 8:59









jrmtmysjrmtmys

112




112







  • 4





    Possible duplicate of Using async/await with a forEach loop

    – Liam
    Mar 7 at 9:04











  • I'd agree with Liam. This is a duplicate and the link he's provided is a good one around using promises. It might be worth stepping away from your actual problem and look at async, promises and promise.all before returning to your problem.

    – Chris Adams
    Mar 7 at 9:10






  • 1





    Basically, if you just want to run all the async requests in parallel and then await them all, you could do something like this: return await Promise.all(idArr.map(id => callSomeApi(id)))

    – noseratio
    Mar 7 at 9:16







  • 1





    @noseratio, your simple solution worked for me! Thank you very much! :)

    – jrmtmys
    Mar 15 at 6:16












  • 4





    Possible duplicate of Using async/await with a forEach loop

    – Liam
    Mar 7 at 9:04











  • I'd agree with Liam. This is a duplicate and the link he's provided is a good one around using promises. It might be worth stepping away from your actual problem and look at async, promises and promise.all before returning to your problem.

    – Chris Adams
    Mar 7 at 9:10






  • 1





    Basically, if you just want to run all the async requests in parallel and then await them all, you could do something like this: return await Promise.all(idArr.map(id => callSomeApi(id)))

    – noseratio
    Mar 7 at 9:16







  • 1





    @noseratio, your simple solution worked for me! Thank you very much! :)

    – jrmtmys
    Mar 15 at 6:16







4




4





Possible duplicate of Using async/await with a forEach loop

– Liam
Mar 7 at 9:04





Possible duplicate of Using async/await with a forEach loop

– Liam
Mar 7 at 9:04













I'd agree with Liam. This is a duplicate and the link he's provided is a good one around using promises. It might be worth stepping away from your actual problem and look at async, promises and promise.all before returning to your problem.

– Chris Adams
Mar 7 at 9:10





I'd agree with Liam. This is a duplicate and the link he's provided is a good one around using promises. It might be worth stepping away from your actual problem and look at async, promises and promise.all before returning to your problem.

– Chris Adams
Mar 7 at 9:10




1




1





Basically, if you just want to run all the async requests in parallel and then await them all, you could do something like this: return await Promise.all(idArr.map(id => callSomeApi(id)))

– noseratio
Mar 7 at 9:16






Basically, if you just want to run all the async requests in parallel and then await them all, you could do something like this: return await Promise.all(idArr.map(id => callSomeApi(id)))

– noseratio
Mar 7 at 9:16





1




1





@noseratio, your simple solution worked for me! Thank you very much! :)

– jrmtmys
Mar 15 at 6:16





@noseratio, your simple solution worked for me! Thank you very much! :)

– jrmtmys
Mar 15 at 6:16












1 Answer
1






active

oldest

votes


















-1














You could start all the Tasks and then await Task.WhenAll(...);



I don't know how to do it in your language, but you'll get the gist:



List<Task<returnType>> tasks = new List<Task<returnType>>();
// start all tasks, don't await for the result yet
for (int i=0; i<idArr.Length; ++i)

Task task = callSomeApi(idArr[i]);
tasks.Add(task);


// wait until all tasks finished:
await Task.Wait(tasks);

// if desired use Task.Result to use the return value:
foreach(Task<returnType> task in tasks)

var result = task.Result;
ProcessResult(result);



If you don't want to wait for all tasks to finish, but want to process the result as soon as one of the tasks is finished, use Task.WhenAny, and remove the finished task from the collection of awaited tasks. Use a HashSet for fast removal



HashSet<Task<returnType>> tasks = new HashSet<Task<returnType>>();
// start all tasks, don't await for the result:
for (int i=0; i<idArr.Length; ++i)

Task<returnType> task = callSomeApi(idArr[i]);
tasks.Add(task);


// as long as there are tasks in the HashSet,
// await until any of the tasks in the HashSet is finished:
while(tasks.Any())

Task finishedTask = await Task.WhenAny(tasks);
tasks.Remove(finishedTask);
ProcessResult(finishedTask.Result); // only if there is a result






share|improve this answer























  • Apparently someone doesn't like this answer and downvoted me. Couldn't he just write as a comment what is wrong? If it is because it is not in VB: in future someone might have the same problem in C#. Shall I just delete this answer?

    – Harald Coppoolse
    Mar 12 at 15:09










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55039745%2fhow-to-properly-do-an-asynchronous-call-in-a-for-loop%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









-1














You could start all the Tasks and then await Task.WhenAll(...);



I don't know how to do it in your language, but you'll get the gist:



List<Task<returnType>> tasks = new List<Task<returnType>>();
// start all tasks, don't await for the result yet
for (int i=0; i<idArr.Length; ++i)

Task task = callSomeApi(idArr[i]);
tasks.Add(task);


// wait until all tasks finished:
await Task.Wait(tasks);

// if desired use Task.Result to use the return value:
foreach(Task<returnType> task in tasks)

var result = task.Result;
ProcessResult(result);



If you don't want to wait for all tasks to finish, but want to process the result as soon as one of the tasks is finished, use Task.WhenAny, and remove the finished task from the collection of awaited tasks. Use a HashSet for fast removal



HashSet<Task<returnType>> tasks = new HashSet<Task<returnType>>();
// start all tasks, don't await for the result:
for (int i=0; i<idArr.Length; ++i)

Task<returnType> task = callSomeApi(idArr[i]);
tasks.Add(task);


// as long as there are tasks in the HashSet,
// await until any of the tasks in the HashSet is finished:
while(tasks.Any())

Task finishedTask = await Task.WhenAny(tasks);
tasks.Remove(finishedTask);
ProcessResult(finishedTask.Result); // only if there is a result






share|improve this answer























  • Apparently someone doesn't like this answer and downvoted me. Couldn't he just write as a comment what is wrong? If it is because it is not in VB: in future someone might have the same problem in C#. Shall I just delete this answer?

    – Harald Coppoolse
    Mar 12 at 15:09















-1














You could start all the Tasks and then await Task.WhenAll(...);



I don't know how to do it in your language, but you'll get the gist:



List<Task<returnType>> tasks = new List<Task<returnType>>();
// start all tasks, don't await for the result yet
for (int i=0; i<idArr.Length; ++i)

Task task = callSomeApi(idArr[i]);
tasks.Add(task);


// wait until all tasks finished:
await Task.Wait(tasks);

// if desired use Task.Result to use the return value:
foreach(Task<returnType> task in tasks)

var result = task.Result;
ProcessResult(result);



If you don't want to wait for all tasks to finish, but want to process the result as soon as one of the tasks is finished, use Task.WhenAny, and remove the finished task from the collection of awaited tasks. Use a HashSet for fast removal



HashSet<Task<returnType>> tasks = new HashSet<Task<returnType>>();
// start all tasks, don't await for the result:
for (int i=0; i<idArr.Length; ++i)

Task<returnType> task = callSomeApi(idArr[i]);
tasks.Add(task);


// as long as there are tasks in the HashSet,
// await until any of the tasks in the HashSet is finished:
while(tasks.Any())

Task finishedTask = await Task.WhenAny(tasks);
tasks.Remove(finishedTask);
ProcessResult(finishedTask.Result); // only if there is a result






share|improve this answer























  • Apparently someone doesn't like this answer and downvoted me. Couldn't he just write as a comment what is wrong? If it is because it is not in VB: in future someone might have the same problem in C#. Shall I just delete this answer?

    – Harald Coppoolse
    Mar 12 at 15:09













-1












-1








-1







You could start all the Tasks and then await Task.WhenAll(...);



I don't know how to do it in your language, but you'll get the gist:



List<Task<returnType>> tasks = new List<Task<returnType>>();
// start all tasks, don't await for the result yet
for (int i=0; i<idArr.Length; ++i)

Task task = callSomeApi(idArr[i]);
tasks.Add(task);


// wait until all tasks finished:
await Task.Wait(tasks);

// if desired use Task.Result to use the return value:
foreach(Task<returnType> task in tasks)

var result = task.Result;
ProcessResult(result);



If you don't want to wait for all tasks to finish, but want to process the result as soon as one of the tasks is finished, use Task.WhenAny, and remove the finished task from the collection of awaited tasks. Use a HashSet for fast removal



HashSet<Task<returnType>> tasks = new HashSet<Task<returnType>>();
// start all tasks, don't await for the result:
for (int i=0; i<idArr.Length; ++i)

Task<returnType> task = callSomeApi(idArr[i]);
tasks.Add(task);


// as long as there are tasks in the HashSet,
// await until any of the tasks in the HashSet is finished:
while(tasks.Any())

Task finishedTask = await Task.WhenAny(tasks);
tasks.Remove(finishedTask);
ProcessResult(finishedTask.Result); // only if there is a result






share|improve this answer













You could start all the Tasks and then await Task.WhenAll(...);



I don't know how to do it in your language, but you'll get the gist:



List<Task<returnType>> tasks = new List<Task<returnType>>();
// start all tasks, don't await for the result yet
for (int i=0; i<idArr.Length; ++i)

Task task = callSomeApi(idArr[i]);
tasks.Add(task);


// wait until all tasks finished:
await Task.Wait(tasks);

// if desired use Task.Result to use the return value:
foreach(Task<returnType> task in tasks)

var result = task.Result;
ProcessResult(result);



If you don't want to wait for all tasks to finish, but want to process the result as soon as one of the tasks is finished, use Task.WhenAny, and remove the finished task from the collection of awaited tasks. Use a HashSet for fast removal



HashSet<Task<returnType>> tasks = new HashSet<Task<returnType>>();
// start all tasks, don't await for the result:
for (int i=0; i<idArr.Length; ++i)

Task<returnType> task = callSomeApi(idArr[i]);
tasks.Add(task);


// as long as there are tasks in the HashSet,
// await until any of the tasks in the HashSet is finished:
while(tasks.Any())

Task finishedTask = await Task.WhenAny(tasks);
tasks.Remove(finishedTask);
ProcessResult(finishedTask.Result); // only if there is a result







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 12 at 13:03









Harald CoppoolseHarald Coppoolse

13.2k13064




13.2k13064












  • Apparently someone doesn't like this answer and downvoted me. Couldn't he just write as a comment what is wrong? If it is because it is not in VB: in future someone might have the same problem in C#. Shall I just delete this answer?

    – Harald Coppoolse
    Mar 12 at 15:09

















  • Apparently someone doesn't like this answer and downvoted me. Couldn't he just write as a comment what is wrong? If it is because it is not in VB: in future someone might have the same problem in C#. Shall I just delete this answer?

    – Harald Coppoolse
    Mar 12 at 15:09
















Apparently someone doesn't like this answer and downvoted me. Couldn't he just write as a comment what is wrong? If it is because it is not in VB: in future someone might have the same problem in C#. Shall I just delete this answer?

– Harald Coppoolse
Mar 12 at 15:09





Apparently someone doesn't like this answer and downvoted me. Couldn't he just write as a comment what is wrong? If it is because it is not in VB: in future someone might have the same problem in C#. Shall I just delete this answer?

– Harald Coppoolse
Mar 12 at 15:09



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55039745%2fhow-to-properly-do-an-asynchronous-call-in-a-for-loop%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

1928 у кіно

Захаров Федір Захарович

Ель Греко