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
Alexander Paudak
1551 silver badge13 bronze badges
-
Does this answer your question? Callback function exampleTân– Tân2020年11月05日 06:22:43 +00:00Commented Nov 5, 2020 at 6:22
-
Dup: Calling a callback in javascriptTân– Tân2020年11月05日 06:23:42 +00:00Commented Nov 5, 2020 at 6:23
-
Dup: Create a custom callback in JavaScriptTân– Tân2020年11月05日 06:24:45 +00:00Commented Nov 5, 2020 at 6:24
-
How does this callback works?Alexander Paudak– Alexander Paudak2020年11月05日 06:25:48 +00:00Commented Nov 5, 2020 at 6:25
1 Answer 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
syarul
2,2053 gold badges23 silver badges22 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Alexander Paudak
Thank you very much sir. Is
Promise a built in function in JavaScript?syarul
yep @AlexanderPaudak
Explore related questions
See similar questions with these tags.
lang-js