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

Javascript is not returning objects as expected

Javascript (or Node.js) is not returning objects as expected.

The following code logs an empty array.

const _sodium = require('libsodium-wrappers');

const sodium = (async () => {
  await _sodium.ready;
  return _sodium;
})();

console.log(Object.getOwnPropertyNames(sodium));

On the other hand, the following code works as expected.

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

const _sodium = require('libsodium-wrappers');

(async () => {
  await _sodium.ready;
  const sodium = _sodium;
  console.log(Object.getOwnPropertyNames(sodium));
})();

In the first code snippet, it seems like the sodium object is tied to its lexical environment, which would explain why an empty array is printed. I would be interested in what’s going on here (including an explanation of what’s going on under the hood). Thanks.

>Solution :

It’s not about lexical context.

You just not awaiting for ready in the first example.

First example simplified:

(async() => {
  console.log('start')
  await new Promise(r => setTimeout(r, 3000))
  console.log('finish')
})()

Second example simplified:

console.log('start');
(async() => {
  await new Promise(r => setTimeout(r, 3000))
})();
console.log('finish')
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