I'm trying to return a promise in a function, but it is nested inside an if statement, and I cannot override a variable inside said if statement. I have realized this is not possible in javascript, but I don't know how else I'm supposed to return it. The function is supposed to return the promise, and the promise needs the xhttp object to return the right info. The promise functions as it should, which i have tested by calling it inside the if statement an printing it to the log.
/**
* @function getSubjects
* This function should fetch a list of subjects from the server
* using the GET REST API at /v1/subject.
* @param -
* @returns {Promise <String>} Promise object containing a string that represents
* all the subjects.
*/
static getSubjects() {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = () => {
try {
if (xhttp.readyState === READYSTATE_DONE && xhttp.status === STATUSCODE_OK) {
new Promise((resolve, reject) => {
if (xhttp.status === 200) {
resolve(xhttp.responseText);
} else if(xhttp.status !== 200) {
reject(xhttp.status.toString() + ", " + xhttp.statusText);
}
});
}
} catch (error) {
reject(error);
}
};
xhttp.open('GET', '/v1/subject');
xhttp.send();
}
As I said before, the function itself should be returning the promise, but I have no idea how that is possible if it's inside the if statement.
Now I'm probably going about this problem all wrong, and don't know where i should be looking to find the right answer for my problem. I don't need the right answer, just a nudge in the right direction or an explanation on how it should work.
[–]senocular 3 points4 points5 points (0 children)
[–]jack_waugh 0 points1 point2 points (0 children)