Javascript 无法在节点js中的函数外看到变量?
我需要使index_to_write变量在函数外部可见。我怎样才能做到这一点Javascript 无法在节点js中的函数外看到变量?,javascript,node.js,variables,asynchronous,xlsx-populate,Javascript,Node.js,Variables,Asynchronous,Xlsx Populate,我需要使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 &a
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");
constxlsxplopulate=require('xlsx-populate');
让发现=错误;
设i=1;
让索引_to_write=0;
XlsxPopulate.fromFileAsync(“todo list.xlsx”)
。然后(工作簿=>{
而(i由于您在函数外部声明了变量,您可以看到它。如果不是这样,您将得到未定义的结果,而不是0
但是,xlsxplopulate.fromFileAsync是一个异步函数,它返回一个承诺,并且在调用该方法时不必立即运行该承诺。因此,在解析该承诺之前,控制台行将运行
因此,执行顺序是:
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 => { ...
这回答了你的问题吗?没有。事实上,我在问我的问题之前看过了,没有,但是谢谢你。@ASDFGERTETHE非常感谢你!应该是在那之后,而不是之前,但我设法解决了!谢谢你!!!不知道这一点。他们关闭了我的问题,所以我不得不删除它,但我非常感谢!!圣诞快乐!