1

I would like to add element an array according to another array. I do something like this with Javascript but the result is always empty:

list2 = []

list1.forEach(element => { 
  doSomething1()
    .then( something1 => { return doSomething2(something1) } )
    .then( something2 => { return doSomething3(something2) } )
    .then( something3 => if (something3 != null) { list2.push(element) } )

})

console.log(list2) // always empty

Can you help me?

Joker
  • 33
  • 7

1 Answers1

0

Than your condition most likely never resolves to true. You can debug by adding a console.log above the expression and see if any of the conditions are met. Otherwise the code looks fine.

If your forEach callback is async you will have to make sure you create an array of promises and wait for all of them to resolve (await Promise.all(...)).

Bitmonk
  • 61
  • 3
  • The question doesn't contain enough information to post a useful answer. –  Dec 14 '20 at 13:24
  • Well he posted a theoretical question so I answered theoretically.. But I guess you're right. Will keep that in mind for other answers in the future. – Bitmonk Dec 14 '20 at 13:37
  • OP has just fixed their question and you hit the nail on the head, however that means OP's question is a duplicate: https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron –  Dec 14 '20 at 13:56
  • Thank you for all your answer. I will take time to understand the explanation in the duplicated post and understand this asynchronicity. – Joker Dec 14 '20 at 14:01