Click here to Skip to main content
15,035,866 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I'm using await in ajax call within async function but still is gives Synctax Error: await is only valid in async function.

What I have tried:

JavaScript
function Function2(){
  //Somelogic
}


async function GetDetails(id) {
    $.ajax({
        url: "/url",
        data: { id: id},
        dataType: "json",
        type: "GET",
        success: function (data) {
           await Function2();
        }
    });
Posted
Updated 6-Jun-19 4:34am

1 solution

The GetDetails function is marked as async; the AJAX success callback function is not.

Rather than using a callback function, you can simply await the $.ajax function:
JavaScript
async function GetDetails(id) {
    var data = await $.ajax({
        url: "/url",
        data: { id: id },
        dataType: "json",
        type: "GET"
    });
    
    // Do stuff with the returned data here...
}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900