1

Based on xlsx github documentation, i made this function to return a json object. This is a method i tried:

function getData(){
    var data; 
    var url = "Book1.xlsx";
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.responseType = "arraybuffer";

    req.onload = function(e) {
        var data = new Uint8Array(req.response);
        var wb = XLSX.read(data, {type:"array"});

        var ws = wb.Sheets['Sheet1'];
        data = XLSX.utils.sheet_to_json(ws);
        //console.log(data);
    }
    //return data;
    req.send();
}

My question is how can i return data so that i'll be able to use it in my other function? My problem is i have a lot of XMLHttpRequest() just to read my Book1.xlsx. Hope someone can help.

  • Does this answer your question? [Callback function example](https://stackoverflow.com/questions/22442321/callback-function-example) – Tân Nov 05 '20 at 06:22
  • Dup: [Calling a callback in javascript](https://stackoverflow.com/questions/3841454/calling-a-callback-in-javascript?rq=1) – Tân Nov 05 '20 at 06:23
  • Dup: [Create a custom callback in JavaScript](https://stackoverflow.com/questions/2190850/create-a-custom-callback-in-javascript) – Tân Nov 05 '20 at 06:24
  • How does this callback works? – Alexander Paudak Nov 05 '20 at 06:25

1 Answers1

1
function getData(cb){
    var data; 
    var url = "Book1.xlsx";
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.responseType = "arraybuffer";

    req.onload = function(e) {
        var data = new Uint8Array(req.response);
        var wb = XLSX.read(data, {type:"array"});

        var ws = wb.Sheets['Sheet1'];
        data = XLSX.utils.sheet_to_json(ws);
        cb(data)
        //console.log(data);
    }
    //return data;
    req.send();
}

const d = new Promise(resolve =>
    getData(resolve)
) 

d.then(data => { 
    console.log(data) 
})
syarul
  • 2,161
  • 2
  • 20
  • 22