在JS中使用Excel文件中的数值。

huangapple go评论73阅读模式
英文:

Using values from an excel file in JS

问题

以下是翻译好的部分:

  1. 我应该如何在完成 readXlsxFile 过程后能够访问 results
  2. 我想让计算机在每行打印后等待1秒钟。我无法让它正常工作。
  3. 我尝试过 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:

  1. How can I make that I should be able to access results after having finised *readXlsxFile * procedure?
  2. I would like to make the computer to wait 1 second after consoling each line.
    I was not able to get it to work
  3. One of my attempts was readXlsx().then(()=>{}) but it also gave me an error. Why?
const readXlsxFile = require(&quot;read-excel-file/node&quot;);
const fs = require(&#39;fs&#39;)
// const results = [];
var results = [];
let maxRow

function sleep(ms) {
    return new Promise(resolve =&gt; setTimeout(resolve, ms));
}

function readXlsx() {
  
  readXlsxFile(&#39;./myfile.xlsx&#39;)
    .then((rows) =&gt; {
      console.log(&quot;Wait!!&quot;)
      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&lt;maxRow-1; nRow++) {
        if (nRow &lt;= 10) {
          console.log(nRow)
          console.log(results[0][nRow][0])
          console.log(results[0][nRow][1])
          console.log(results[0][nRow][2])
          console.log(&#39;---&#39;)
        }
        // .then(()=&gt;{sleep(500)})      
      }

      return Promise.resolve(&quot;Success&quot;)
  })

}

function testSleep() {
    console.log(&quot;Hello&quot;);
      sleep(2000).then(() =&gt; { console.log(&quot;World!&quot;); });
  
  // console.log(results)
  }


readXlsx()

TIA

答案1

得分: 0

现代JavaScript中的一个基本概念是promise,您可以在这里阅读更多相关信息。了解这个背景对于理解您的问题的答案非常重要。

  1. 有两种方法可以实现这个,一种是使用.then()(就像您目前所使用的方式),另一种是使用await。在处理promise时,我发现使用await更容易理解(而且更适合您当前代码的结构),您可以在这里了解更多相关信息。下面是相同的代码,改用awaitasync
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,但这是根据您当前的设置方式来工作的。

  1. 我认为您对.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)
  }
}

这样可以在整个函数内正确地阻止执行。

  1. 我不知道您遇到了什么错误,所以我无法知道具体情况,但可能是因为在那个时候,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.

  1. There are two ways of doing this, using .then() (like you are), or using await. I find await 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, using await and async instead:
const readXlsxFile = require(&quot;read-excel-file/node&quot;);
const fs = require(&#39;fs&#39;)
// const results = [];
var results = [];
let maxRow

function sleep(ms) {
    return new Promise(resolve =&gt; setTimeout(resolve, ms));
}

// V - Notice that this is an &quot;async&quot; function
async function readXlsx() {
  const rows = await readXlsxFile(&#39;./myfile.xlsx&#39;)
  results.push(rows)

  const maxRow = rows.length

  for (var nRow = 1; nRow &lt; maxRow - 1; nRow++) {
    console.log(nRow)
    console.log()
    console.log(results[0][nRow][1])
    console.log(results[0][nRow][2])
    console.log(&#39;---&#39;)
  }
}

because we are now awaiting 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&#39;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.

  1. 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 same async/await code above, you can now use sleep as intended:
async function readXlsx() {
  const rows = await readXlsxFile(&#39;./myfile.xlsx&#39;)
  results.push(rows)

  const maxRow = rows.length

  for (var nRow = 1; nRow &lt; maxRow - 1; nRow++) {
    console.log(nRow)
    console.log()
    console.log(results[0][nRow][1])
    console.log(results[0][nRow][2])
    console.log(&#39;---&#39;)
    
    await sleep(1000)
  }
}

which properly blocks execution within the entire function.

  1. 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)

huangapple
  • 本文由 发表于 2023年7月7日 06:15:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76632824.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定