0

I am trying to return a value, which should be an array (reading the text from inside button tags) but my return statement comes up undefined, I believe because my return statement executes before the for loop is finished and the value is assigned.

I have been looking up async, await, promises, and whatnot but I just can't seem to tie it into what I am trying to accomplish.

I believe this is different from the tagged duplicate because I am not using Ajax.

function getComponentsButtons(component){

  let currentButton = []
  let buttonArray = []
  let path = `../src/components/${component}/index.js`;

  /* Reading each index.js */
  fs.readFile(path, "utf8", function(err, data) {
    /* Walking along and seeing if there is a <button tag */

    for(let j = 0; j < data.length; j++){

      if(data.slice(j, j + 7) === '<button'){
        /* if there is a <button tag, walk til you see the closing tag >, get the value until you reach the < tag */

        while(data[j] !== '>'){
          j++;
        }

        while(data[j] !== '<'){
          j++;
          currentButton.push(data[j]);
        }

        currentButton.pop();
        currentButton = currentButton.join("");
        buttonArray.push(currentButton);
        currentButton = []

      }

    }

  }); // end of read file

  return buttonArray;

}

I am hoping to be able to return the filled buttonArray.

Danjuro
  • 141
  • 1
  • 8
  • You can use `readFileSync` instead of `readFile` – Nir Alfasi Jun 30 '19 at 02:08
  • @alfasin thank you for the help. I actually tried readFileSync but get the same issue unfortunately. – Danjuro Jun 30 '19 at 02:17
  • Try `const content = readFileSync(...);` and then the rest of the code (in other words, remove the code from the callback and set it to be after the file was read). – Nir Alfasi Jun 30 '19 at 04:18

0 Answers0