Skip to content
Advertisement

Getting a value from Javascript Async request and use it for further logic

I want to get a value from the async javascript call and store the retuned value in a variable and then write some logic based on the value.

My Javascript file looks like this.

function getAjax() {
    let mycall;
    myCall = $.ajax({
        type: "GET",
        url: "https://api.github.com/users",
        dataType: "json"
    })
    return myCall;
}
async function myBlur1() {
    const myret = await getAjax();
    // if(myret[0].login == "mojombo"){
    //     return true;
    // }
    // else {return false;}
    console.log(myret);
    return myret[0].login;
}

Now in my HTML I would like to call the myBlur1 function and store the return value and then outside the function call I would like to build logic based on the return value.

Here is my HTML file.

<body>
    <div id="message"></div>
    <script>
        let failed = false;
        (async () => {
            console.log("I am inside IIFE");
            let ret = await myBlur1();
            if(ret == "mojombo")
            {
                failed = true;
            }
        })();
        
        if(failed){
            console.log("I am ready.");
        }
        else {
            console.log("I am not yet ready.")
        }
    </script>
</body>

I am always getting I am inside IIFE I am not yet ready. and after that the return arrays from async call.

Please help.

Advertisement

Answer

To get your result, you have to make the scope inside script tag compatible with step by step asynchronous operations. so put whole code inside script in async IIFE.

<body>
    <div id="message"></div>
    <script>
      (async () => {
        let failed = false;
        await (async () => {
            console.log("I am inside IIFE");
            let ret = await myBlur1();
            if(ret == "mojombo")
            {
                failed = true;
            }
        })();
        
        if(failed){
            console.log("I am ready.");
        }
        else {
            console.log("I am not yet ready.")
        }
     })();
    </script>
</body>

more simplified updated version(as we are already inside async function)

<body>
    <div id="message"></div>
    <script>
      (async () => {

        let failed = false;
        let ret = await myBlur1();

        if(ret == "mojombo") {
           failed = true;
        }

        if(failed){
            console.log("I am ready.");
        }
        else {
            console.log("I am not yet ready.")
        }
     })();
    </script>
</body>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement