Home > other >  async() function not running in javascript
async() function not running in javascript

Time:10-15

I am trying to check for a response from my server in javascript like this:

function pending() {
    return $.ajax({
        url: 'report.php',
        type: 'POST',
        data: {
            "input": "update_pending_records"
        }
    })
}
if (t == "Admin") {
    console.log(t); //shows Admin here
    /*---CODE IS DEAD FROM BELOW. DON'T KNOW WHY-----*/
    async () => {
        console.log(t); //shows nothing
        var response = await pending();
        if (response == "something") {
            //do something here
        }
    }
    /*----------------------------------------------*/
}

The async() function prints nothing. In fact the variables which are already declared (like t) prints nothing upon going inside the async() function. Why is that?

EDIT: After a long time, I got these messages printed in my console:

Unchecked runtime.lastError: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received

Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received

CodePudding user response:

You can call the anonymous function like this by self-invoking it:

(async () => {
    console.log(t); //shows nothing
    var response = await pending();
    if (response == "something") {
        //do something here
    }
})();

Or if your outer context is async, you can call it like this:

const myFunc = async () => {
    console.log(t); //shows nothing
    var response = await pending();
    if (response == "something") {
        //do something here
    }
}
await myFunc();

CodePudding user response:

Question is not clear, If you are trying to make call only if it is admin then you can do this way

function pending() {
    if (t == "Admin") {
        $.ajax({
            url: 'report.php',
            type: 'POST',
            data: {
                "input": "update_pending_records"
            },
            success: function(response) {
                if (response == "something") {
                    //do something here
                }
            }
        })
    }
}

pending()

OR this way

(async () => {
    if (t == "Admin") {
        var response = await pending();
        if (response == "something") {
            //do something here
        }
    }
})();
  • Related