My getJSON function is not returning the array I need. I have been attempting to use await/async, but it seems like there might be an error in my approach.
The methods .map and .filter are supposed to be synchronous, but even adding await does not seem to work as expected.
$(function() {
$("#roll").click(async function() {
var x = await fetchTreasure()
chrome.extension.getBackgroundPage().console.log(x)
});
});
function fetchTreasure() {
var sizeValue = $('input[name=size]:checked').val();
var crValue = $('input[name=challenge]:checked').val();
var die = Math.floor((Math.random() * 100) + 1);
var url = "";
if (sizeValue == "individual") {
url = chrome.runtime.getURL("treasure_individual.json");
} else {
url = chrome.runtime.getURL("treasure_horde.json");
};
$.getJSON(url, function(data) {
var match = data.treasure.filter(function (e) {
return e.cr == crValue;
});
for (i in match[0].roll) {
var str = match[0].roll[i].d100;
var arr = str.match(/([0-9]+)/g);
var levels = $.map(arr, function (x) {
return parseInt(x, 10);
});
if (die == levels[0] || die >= levels[0] && die <= levels[1]) {
chrome.extension.getBackgroundPage().console.log(levels);
return levels;
} else {
return die;
}
};
});
};
Edit: I now realize that await still requires a Promise. However, I am still unable to achieve the desired result. I tried encapsulating the getJson function with a Promise, but the return for levels is still not working as intended.
function fetchTreasure() {
var sizeValue = $('input[name=size]:checked').val();
var crValue = $('input[name=challenge]:checked').val();
var die = Math.floor((Math.random() * 100) + 1);
var url = "";
if (sizeValue == "individual") {
url = chrome.runtime.getURL("treasure_individual.json");
} else {
url = chrome.runtime.getURL("treasure_horde.json");
};
return new Promise(resolve => {
$.getJSON(url, function(data) {
var match = data.treasure.filter(function (e) {
return e.cr == crValue;
});
for (i in match[0].roll) {
var str = match[0].roll[i].d100;
var arr = str.match(/([0-9]+)/g);
var levels = $.map(arr, function (x) {
return parseInt(x, 10);
});
if (die == levels[0] || die >= levels[0] && die <= levels[1]) {
//chrome.extension.getBackgroundPage().console.log(levels);
return levels;
}
};
});
});
};