-2

I want to read a variable defined outside an asynchronous function. But the console tells me that my variable is not defined. selectors is not defined

How can I solve this or what am I not understanding ?

File 1 : index.js

import { getSpecs } from "./getSpecs.js";

let file = fs.readFileSync('selectors.json');
let selectors = JSON.parse(file);
await getSpecs(selectors);

File 2 : getSpecs.js

export let getSpecs = async function(selectors)
{
    var1 = document.querySelector(selectors.seller).innerText;
    ....
}
Cosmos
  • 29
  • 5
  • [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call?rq=1) – Andreas Aug 30 '21 at 14:37

3 Answers3

1

You cannot access var1 in getSpecs because they are not declared in the same scope.

Ogie
  • 1,304
  • 2
  • 14
  • 17
  • Yes, this is true. However you could export that variable, but exporting it and importing to the other file will result in circular dependency. You shouldnt do that. Create a file that exports an object with a property, and import it that object. With that you will be able to modify the property. – Totati Aug 30 '21 at 14:44
1

The scope for a variable declared without var/let/const for a module is that module and not the global environment.

Don't use globals. Return the value you care about instead.

import { getSpecs } from "./getSpecs.js";

let var1 = 1;
const var1 = await getSpecs();

File 2 : getSpecs.js

export async function getSpecs()
{
    const var1 = 2;
    return var1;
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

If you will modify the value and return other value, wouldn't it be better to send the value as a parameter to the function?

import { getSpecs } from "./getSpecs.js";

let var1 = 1;
let newVar1 = await getSpecs(var1);

File 2 : getSpecs.js

export async function getSpecs(var1)
{
    const response = var1 + 2;
    return response;
}

Like that?

RAlves
  • 42
  • 2