英文:
Using values from an excel file in JS
问题
以下是翻译好的部分:
- 我应该如何在完成 readXlsxFile 过程后能够访问 results?
- 我想让计算机在每行打印后等待1秒钟。我无法让它正常工作。
- 我尝试过 readXlsx().then(() => {}), 但它也给了我一个错误。
const readXlsxFile = require("read-excel-file/node");
const fs = require('fs');
var results = [];
let maxRow;
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function readXlsx() {
readXlsxFile('./myfile.xlsx')
.then((rows) => {
console.log("等待中!");
results.push(rows); // 将完整结果推入数组
var maxRow = rows.length;
// nRow = 0 将是标题,不会打印
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('---');
}
// .then(() => {sleep(500)})
}
return Promise.resolve("成功");
});
}
function testSleep() {
console.log("你好!");
sleep(2000).then(() => { console.log("世界!"); });
}
readXlsx();
TIA
英文:
am ne in JS
I have several questions:
The code below, it is opening/extracting the information from XLS properly
I would like:
- How can I make that I should be able to access results after having finised *readXlsxFile * procedure?
- I would like to make the computer to wait 1 second after consoling each line.
I was not able to get it to work - One of my attempts was readXlsx().then(()=>{}) but it also gave me an error. Why?
const readXlsxFile = require("read-excel-file/node");
const fs = require('fs')
// const results = [];
var results = [];
let maxRow
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function readXlsx() {
readXlsxFile('./myfile.xlsx')
.then((rows) => {
console.log("Wait!!")
results.push(rows) // Push the complete result into array
// console.log(results)
var maxRow = rows.length
// nRow = 0 Will be the title. WILL NOT CONSOLE
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('---')
}
// .then(()=>{sleep(500)})
}
return Promise.resolve("Success")
})
}
function testSleep() {
console.log("Hello");
sleep(2000).then(() => { console.log("World!"); });
// console.log(results)
}
readXlsx()
TIA
答案1
得分: 0
现代JavaScript中的一个基本概念是promise
,您可以在这里阅读更多相关信息。了解这个背景对于理解您的问题的答案非常重要。
- 有两种方法可以实现这个,一种是使用
.then()
(就像您目前所使用的方式),另一种是使用await
。在处理promise
时,我发现使用await
更容易理解(而且更适合您当前代码的结构),您可以在这里了解更多相关信息。下面是相同的代码,改用await
和async
:
const readXlsxFile = require("read-excel-file/node");
const fs = require('fs')
var results = [];
let maxRow
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// 注意,这是一个“async”函数
async function readXlsx() {
const rows = await readXlsxFile('./myfile.xlsx')
results.push(rows)
const maxRow = rows.length
for (var nRow = 1; nRow < maxRow - 1; nRow++) {
console.log(nRow)
console.log()
console.log(results[0][nRow][1])
console.log(results[0][nRow][2])
console.log('---')
}
}
因为我们现在使用await
等待readXlsxFile
函数的结果,所以在readXlsxFile
完成之前,代码不会继续执行。这样,如果您在其他地方引用这个函数,results
将被正确定义:
// ... 这是您代码的继续部分
async function logMyResults() {
await readXlsx()
// 这将在readXlsx()完成之前不会运行,因为它被“await”
console.log(results)
}
虽然您可能应该只返回results
,但这是根据您当前的设置方式来工作的。
- 我认为您对
.then()
的工作方式有一些误解。.then()
是在promise
完成后运行代码的方式。问题在于,只有您提供给.then()
的函数内的代码将在promise
完成后运行,而其他所有代码将继续运行而不等待。使用上面相同的async/await
代码,您现在可以按预期使用sleep
:
async function readXlsx() {
const rows = await readXlsxFile('./myfile.xlsx')
results.push(rows)
const maxRow = rows.length
for (var nRow = 1; nRow < maxRow - 1; nRow++) {
console.log(nRow)
console.log()
console.log(results[0][nRow][1])
console.log(results[0][nRow][2])
console.log('---')
await sleep(1000)
}
}
这样可以在整个函数内正确地阻止执行。
- 我不知道您遇到了什么错误,所以我无法知道具体情况,但可能是因为在那个时候,
readXlsx
不是一个async
函数,您只能在async
函数(也就是promise
)的结果上调用.then()
。
英文:
A fundamental concept in modern JavaScript is something called a promise
, which you can read more about here. This background is important for you to understand the answers to your questions.
- There are two ways of doing this, using
.then()
(like you are), or usingawait
. I findawait
easier to understand when thinking about promises (and it fits a bit better into the structure of what you're doing), and you can read about it here. Below is the same code, usingawait
andasync
instead:
const readXlsxFile = require("read-excel-file/node");
const fs = require('fs')
// const results = [];
var results = [];
let maxRow
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// V - Notice that this is an "async" function
async function readXlsx() {
const rows = await readXlsxFile('./myfile.xlsx')
results.push(rows)
const maxRow = rows.length
for (var nRow = 1; nRow < maxRow - 1; nRow++) {
console.log(nRow)
console.log()
console.log(results[0][nRow][1])
console.log(results[0][nRow][2])
console.log('---')
}
}
because we are now await
ing the result of the readXlsxFile
function, the code will not continue before readXlsxFile
is finished. This way, if you refer to the function in another area, results
will be properly defined:
// ... this is a continuation of your code
async function logMyResults() {
await readXlsx()
// This will not run until readXlsx() is done, since it's being `await`ed
console.log(results)
}
while you should probably just be returning results
instead, that is how it would work in the way you currently have everything set up.
- I think you were misunderstanding how
.then()
works..then()
is how you would run code after a promise finishes. The problem is that only the code within the function you provide to.then()
will be run after the promise is done, and everything else outside of it will continue running without waiting. Using the sameasync/await
code above, you can now usesleep
as intended:
async function readXlsx() {
const rows = await readXlsxFile('./myfile.xlsx')
results.push(rows)
const maxRow = rows.length
for (var nRow = 1; nRow < maxRow - 1; nRow++) {
console.log(nRow)
console.log()
console.log(results[0][nRow][1])
console.log(results[0][nRow][2])
console.log('---')
await sleep(1000)
}
}
which properly blocks execution within the entire function.
- I don't know what error you got, so I have no way of knowing, but it is probably because, at that time,
readXlsx
was not an async function, and you can only call.then()
on the results of an async function (AKA: a promise)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论