0

This is my code

const someIDs = [1, 2, 3];

const users = someIDs.map(async(ID) => {
    const user = await getUser(ID);
    return user;
});

cosnole.log(users);

This is a simple example in which I wanted to show what I want. How to do asynchronous iteration in map, forEach. without using Promise.all (), for ... of.

  • "*without using Promise.all (), for ... of.*" - why that artificial limitation? And no, it's not possible to do it properly without those. `forEach` cannot be used for asynchronous iteration at all, and `map` requires `Promise.all` as a supplement. – Bergi Aug 21 '19 at 22:00
  • 1
    @Bergi Maybe there’s a way. You just don't know.And this is not a duplicate. –  Aug 21 '19 at 22:10
  • @Bergi maybe there is a solution –  Aug 21 '19 at 22:17
  • 1
    Believe me, I know them. I even do know others, but I doubt they're the ones you are looking for, so I didn't mention them. Your question isn't really specific about what kind of "asynchronous iteration" you are looking for - there are multiple alternatives. How do you want it to work? If the code is exactly what you want, why not just use it - and if it is not exactly what you want, how does it differ from your expectations? This lack of detail made me assume that you don't know of the fine distinctions, and a standard solution is the best choice. If it is not, you need to tell us why. – Bergi Aug 21 '19 at 22:18
  • @Bergi If I ask you this question.How can you rewrite this code without using Promise.all (), for ... of.The answer will be no way.? –  Aug 21 '19 at 22:32
  • @ForestDeath I could rewrite it by implementing the `Promise.all` functionality by hand, or by using recursion. But again, please [edit] your question to tell us why the simple solutions don't work for you, so that we could suggest an appropriate non-standard solution. As it stands, the question is not really answerable, and the duplicate has the best resources on the general topic. I'm happy to reopen when you provide details for what you need. – Bergi Aug 21 '19 at 22:36
  • @Bergi I read this [article](https://lavrton.com/javascript-loops-how-to-handle-async-await-6252dd3c795/).The third paragraph says that it is not always correct to use Promise.all.That's why I'm looking for Another way. –  Aug 21 '19 at 22:53
  • 1
    @ForestDeath It doesn't say that it's wrong to use `Promise.all`. For what situation exactly are you looking for a different way? All that it says is that the concurrent version is not always better than the sequential - either because you don't want them to happen all at once, or because the kind of asynchronous task is not well suited to run in parallel. That's when you would usually go for the sequential solution, or something like limited concurrency (no more than X running tasks at the same time). – Bergi Aug 21 '19 at 23:16
  • @Bergi Thank you for the answer. –  Aug 21 '19 at 23:20

0 Answers0