简体   繁体   中英

array with objects being pushed in it turns out to be empty still

I am declaring an array list_of_blogposts and then I am opening a file to pull data from it, and in it, I am declaring an object blogpost_object in which I am entering key-value pairs. When I console log it inside the opened file code block it does console log properly, but outside it, it shows empty, like in the last line it doesn't work. Can anybody mention whats the reason and solution for it? Thanks, the code is below

const list_of_blogposts = [];

new XLSX()
  .extract("./all_blogposts.xlsx", {
    ignore_header: 2,
    include_empty_rows: false,
    sheet_name: "all_blogposts"
  })
  .on("row", function(row) {
    var blogpost_object = {};
    blogpost_object["title"] = row[2];
    list_of_blogposts.push(blogpost_object);

    console.log(list_of_blogposts);
  });

console.log(list_of_blogposts);

This is because the function(row) {... is a callback function thus it is executed asynchronously. So the flow of execution will be like

  1. execute .on()
  2. call the function in callback function(row) {...
  3. execute the console.log outside the function
  4. finally, the execution of the callback function

Thus, the console.log you have outside the function is executed before the callback function is called so it returns an empty array. The console.log within the function returns the array after the values are pushed.

So what you can do to solve this problem is do whatever you want to do with the array of values within the callback function.

const doAction = (list) => {
   //Do whatever you want
}

const list_of_blogposts = [];

new XLSX()
  .extract("./all_blogposts.xlsx", {
    ignore_header: 2,
    include_empty_rows: false,
    sheet_name: "all_blogposts"
  })
  .on("row", function(row) {
    var blogpost_object = {};
    blogpost_object["title"] = row[2];
    list_of_blogposts.push(blogpost_object);

    console.log(list_of_blogposts);
    doAction(list_of_blogposts)
  });

console.log(list_of_blogposts);

Hope it helped!!!

You can use the .on('end' method for actions you need to perform after all the rows have been read. Similarly, you can use .on('error' for handling error scenarios.

The code can be

const list_of_blogposts = [];
new XLSX()
  .extract("./all_blogposts.xlsx", {
    ignore_header: 2,
    include_empty_rows: false,
    sheet_name: "all_blogposts"
  })
  .on("row", function(row) {
    var blogpost_object = {};
    blogpost_object["title"] = row[2];
    list_of_blogposts.push(blogpost_object);

    console.log(list_of_blogposts);
  }).on('end', function (err) {
    console.log(list_of_blogposts);
    your_method(); // you can perform anything you want after all rows are read
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM