无法在 Node js 的函数外部看到变量?

Cant make a variable be seen outside of a function in Node js?

我需要使 index_to_write 变量在函数外部可见。我怎样才能做到这一点?

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");

我尝试在 index_to_write = i.toString(); 下方添加 return index_to_write;,但没有解决问题。

目前和初始化一样显示0,但应该打印4,如何修复?

非常感谢您!

由于您在函数外部声明变量,因此您可以看到它。如果不是这种情况,您将得到 undefined 而不是 0。

然而,XlsxPopulate.fromFileAsync 是一个异步函数,returns 是一个 promise,当调用该方法时,它不一定会立即 运行。因此,在解决承诺之前,您的控制台行将 运行。

所以执行顺序是:

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 => { ...