0

I call this function from another .js file, and as a response from server there is boolean value.

function submitFormData() {
    let var1 = '';
    submitForm();

    function makeRequest() {
        return new Promise((resolve, reject) => {
            let request = new XMLHttpRequest();
            request.withCredentials = true;
            request.open('POST', api);
            request.onreadystatechange = () => {
                if (request.readyState === 4) {
                    if (request.status >= 200 && request.status < 400) {
                        resolve(request.response);
                    } else {
                        reject(request.response);
                    }
                }
            };
            request.setRequestHeader('Content-Type', 'application/json');
            request.send();
        });
    }
    async function submitForm() {
        try {
            const requestPromise = makeRequest();
            const response = await requestPromise;
            return var1 = response
        }
        catch (errorResponse) {
            alert(errorResponse);
        };
    }
    return var1;
}

As a value in other js file i get empty string, i'm not sure what do i do wrong here.

Djisin
  • 19
  • 5
  • This has nothing to do with `try/catch`, you are just returning the value of `var1` before the asynchronous request has completed and changed the value of `var1` from the empty string you set it to initially.. – Quentin Apr 04 '20 at 12:37
  • @Quentin I have realised as much, but i have no clue how to do it, and since i'm new to programming i don't understand anything on the page you provided. You could have at least try to help since you blocked my question... – Djisin Apr 04 '20 at 14:33
  • The duplicate question has 38 answers! – Quentin Apr 04 '20 at 19:11

0 Answers0