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.

asked Nov 5, 2020 at 6:20
4

1 Answer 1

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) 
})
answered Nov 5, 2020 at 6:32
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much sir. Is Promise a built in function in JavaScript?
yep @AlexanderPaudak

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.