0

I wrote this code and it's works perfect for me. But when i try to convert it to fetch, dosen't work because return a promise. I don't know how to use it as a async false on fetch.

            'getProjectConstants': function(constArray)
            {
                var result='';
                $.ajax({
                type:       "GET",
                url:        `${constProjectBaseUrl}/ajax/getProjectConstants/${constArray}`,
                async:      false,
                dataType:   "json",
                success: function(data) {
                result = data
            }
        });
        return result

I tried to do like this, but dosen't work

        fetch(`${constProjectBaseUrl}/ajax/getProjectConstants/${constArray}`)
        .then((response) => response.json())
        .then((response) => {
             // console.log(response)
             return response
        }) // end of .then((response) => {
        .catch(error => {
             console.log("[ajax.getProjectConstants] Error => " + error);
        }); // end of .catch(error => {
1

1 Answer 1

2

You can try this:

async function getProjectConstants(){
    const json = await (await fetch(`${constProjectBaseUrl}/ajax/getProjectConstants/${constArray}`)).json();
    return json;
}
ajax.getProjectConstants(['PROJECT_PASSWORD_MINIMUM', 'OWNER_NAME', 'DB_TBL_TIME_ZONE']).then((constant) => {
    console.log(constant.OWNER_NAME)
}).catch(console.error);
Sign up to request clarification or add additional context in comments.

6 Comments

Hi @Tanay... Unfortunately it doesn't work, first it returns null and then the result, as if async wasn't working
Can you share the code where you are calling the networkRequest function?
Hi, sure, thanks for quickly reply constant = ajax.getProjectConstants(['PROJECT_PASSWORD_MINIMUM', 'OWNER_NAME', 'DB_TBL_TIME_ZONE']); console.log(constant.OWNER_NAME)
You need to use then and catch here, or use async/await since the object returned is promise
Could you please help me litte bit more. I'm begginer on JS... my strong skills is PhP I dont know how to do what you said on JS :(
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.