偶然的你
2024-01-18 16:23:54
我需要使index_to_write變量在函數(shù)外部可見(jiàn)。我怎樣才能使這成為可能?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");我嘗試return index_to_write;在下面添加index_to_write = i.toString();但它不能解決問(wèn)題。目前,它顯示0,與初始化時(shí)一樣,但它應(yīng)該打印4。如何修復(fù)它?非常感謝您!
1 回答

慕萊塢森
TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
由于您在函數(shù)外部聲明了變量,因此您可以看到它。如果不是這種情況,結(jié)果將是 undefined 而不是 0。
但是 XlsxPopulate.fromFileAsync 是一個(gè)異步函數(shù)并返回一個(gè)承諾,并且在調(diào)用該方法時(shí)不一定會(huì)立即運(yùn)行。因此,您的控制臺(tái)線路將在承諾解決之前運(yùn)行。
所以執(zhí)行順序是:
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 => { ...
添加回答
舉報(bào)
0/150
提交
取消