I need to make the index_to_write variable to be seen outside of the function. How can I make this possible?
const XlsxPopulate = require('xlsx-populate');
let found = false;
let i = 1;
let index_to_write = 0;
XlsxPopulate.fromFileAsync("todo-list.xlsx")
.then(workBook => {
while (i <= 10 && found === false){
const value = workBook.sheet("Do-Shopping").cell("A" + i.toString()).value();
if (value === undefined) {
found = true;
index_to_write = i.toString();
}
i++;
}
});
console.log("A " + index_to_write + " is the first one to be free of data");
I tried to add return index_to_write;
below the index_to_write = i.toString();
but it does not resolve the problem.
Currently, it shows 0, as in the initialization, but it should print 4. How to repair it?
Thank you very much in advanced!
Since you declare the variable outside of the function you can see it. If that was not the case, you would get undefined and not 0 as a result.
However XlsxPopulate.fromFileAsync is an async function and returns a promise, and that will not neccesarily be run imediately when the method is invoked. Therefore your console line will run before the promise is resolved.
So the execution sequence would be:
1. let index_to_write = 0;
2. XlsxPopulate.fromFileAsync("todo-list.xlsx")
3. console.log("A " + index_to_write + " is the first one to be free of data");
4. then(workBook => { ...