JS读取Excel后访问results、延时输出及then调用报错问题
问题解答
1. 如何在readXlsxFile执行完成后访问results变量?
你的readXlsx函数原本没有返回内部的Promise链,外部无法感知异步操作何时结束。要解决这个问题,只需让readXlsx返回readXlsxFile的Promise链,这样就能在外部通过.then或async/await确保在操作完成后访问results。
修改后的readXlsx函数:
function readXlsx() { // 返回Promise链,让外部能监听完成状态 return readXlsxFile('./myfile.xlsx') .then((rows) => { console.log("Wait!!") results.push(rows) // ... 原有循环逻辑 return results; // 可选:把结果返回给外部的then }) }
外部调用示例:
readXlsx().then(() => { console.log(results); // 此时results已被赋值 });
更推荐的做法是放弃全局results,直接在then回调里处理rows,避免全局变量带来的潜在问题。
2. 实现每输出一行后等待1秒
原代码的for循环是同步执行的,sleep仅创建了Promise但没有等待它完成,所以不会产生暂停效果。需要将循环所在的回调改为async函数,用await等待sleep完成。
修改循环部分:
.then(async (rows) => { console.log("Wait!!") var maxRow = rows.length for (var nRow = 1; nRow < maxRow - 1; nRow++) { if (nRow <= 10) { console.log(nRow) console.log(rows[nRow][0]) console.log(rows[nRow][1]) console.log(rows[nRow][2]) console.log('---') await sleep(1000); // 等待1秒后再执行下一次循环 } } return "Success" })
3. 使用readXlsx().then(()=>{})报错的原因
你的readXlsx函数原本没有返回任何Promise,默认返回undefined,而undefined没有.then方法,因此调用readXlsx().then()会触发“Cannot read properties of undefined (reading 'then')”错误。
解决方法很简单:在readXlsx函数里返回内部的readXlsxFile Promise链,也就是加上return关键字:
function readXlsx() { // 返回Promise,让外部能调用then return readXlsxFile('./myfile.xlsx') .then((rows) => { // ... 原有逻辑 return "Success" }) }
完整修改后的代码
const readXlsxFile = require("read-excel-file/node"); const fs = require('fs') var results = []; function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } function readXlsx() { return readXlsxFile('./myfile.xlsx') .then(async (rows) => { console.log("Wait!!") results.push(rows) var maxRow = rows.length for (var nRow = 1; nRow < maxRow - 1; nRow++) { if (nRow <= 10) { console.log(nRow) console.log(results[0][nRow][0]) console.log(results[0][nRow][1]) console.log(results[0][nRow][2]) console.log('---') await sleep(1000); } } return "Success" }) } readXlsx().then((msg) => { console.log(msg); console.log(results); });
内容的提问来源于stack exchange,提问作者Benny
相关产品推荐
相关产品推荐

