Home > Net >  Passing argument to async / await function returns "undefined"
Passing argument to async / await function returns "undefined"

Time:04-21

When posting data to an API and get a response, if I hardcode the body data inside the fetch call (body: "XYZ12345") it works fine, this is an example:

            const vatValidationRequest =
                fetch(
                    '/api/vies/validateVAT.php', {
                        method: 'POST',
                        body: "XYZ12345",
                        headers: {
                            'Content-Type': 'application/text'
                        }
                    })
                .then((response) => response.text())
                .then((responseText) => {
                    return responseText;
                });


            const validateVAT = async () => {
                const viesResponse = await vatValidationRequest;
                console.log(viesResponse);
            };

            validateVAT();

However, if I try to pass the body data as an argument (body: vatNumber), the validateVAT() function returns "undefined". This is what's not working:

            const vatValidationRequest = (vatNumber) => {
                fetch(
                    '/api/vies/validateVAT.php', {
                        method: 'POST',
                        body: vatNumber,
                        headers: {
                            'Content-Type': 'application/text'
                        }
                    })
                .then((response) => response.text())
                .then((responseText) => {
                    return responseText;
                });
            }


            const validateVAT = async (vatNumber) => {
                const viesResponse = await vatValidationRequest(vatNumber);
                console.log(viesResponse);
            };

            validateVAT("XYZ12345");

Any clues about how to pass the argument to the async function? thanks!

CodePudding user response:

The problem is that you are not returning the response from the method. You should do this:

            const vatValidationRequest = (vatNumber) => {
                return fetch(
                    '/api/vies/validateVAT.php', {
                        method: 'POST',
                        body: vatNumber,
                        headers: {
                            'Content-Type': 'application/text'
                        }
                    })
                .then((response) => response.text())
                .then((responseText) => {
                    return responseText;
                });
            }


            const validateVAT = async (vatNumber) => {
                const viesResponse = await vatValidationRequest(vatNumber);
                console.log(viesResponse);
            };

            validateVAT("XYZ12345");
  • Related