Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For loop value in Promise.then() inside

I have a question about promise.then() inside a for loop in node.js.

For a code like this:

const arrayObject = [
  {
    id: 1234,
    toto: 'abc'
  },
  {
    id: 5678,
    toto: 'def'
  },
  {
    id: 910,
    toto: 'ghi'
  },
]
const finalArray = []
let promiseArray = []
for (let singleObject of arrayObject) {
    promiseArray.push(
        Promise.function(...).then(res => {
            if (res === true) {
                finalArray.push(singleObject)
            }
        })
    )
}
await Promise.all(promiseArray)

If the singleObject before the promise is ‘id: 1234’, will the singleObject in the promise is the same ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I know that with tests I have done it is but I can’t find any documentation/example stating that the singleObject in the promise.then will be the same as the singleObject before the promise.

Does the singleObject in the promise.then is always in the same scope as the singleObject before the promise ?

>Solution :

Yes, both variables contain references to the same object. It has nothing to do with Promise.then. It’s the closure of the arrow function

res => { if (res === true) { finalArray.push(singleObject) } } 

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

Even the global scope is part of the closure scope chain:

Every closure has three scopes:

  • Local Scope (Own scope)
  • Outer Functions Scope
  • Global Scope
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading