0

I have a function that returns an ajax get response:

var myAjaxFunction = function () {
   $.get("/Page1/Index?handler=MyFunction",
        { itemId: itemId})
       .done(function (response) {
           return response;
        })
        .fail(function () {
            return null;
        });
}

This function is called and response is assigned to a variable.

var pendingOperation = myAjaxFunction();

Debugging, the problem that I'm seeing is that if I put a breakpoint on or after the pendingOperation line, it remains undefined. If I continue after the breakpoint, it then hits myAjaxFunction and I can see it tries to return a response containing data. By that point, it is already too late and pendingOperation is undefined. How can I guarantee that myAjaxFunction waits for the get/fetch of data and successfully returns my response before moving on?

nhershy
  • 643
  • 1
  • 6
  • 20
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Calvin Nunes Jan 21 '20 at 20:07

1 Answers1

0

Your MyFunction must use .Wait() inside.

For example,

public IActionResult OnGetMyFunction(int itemId)
{
     var list = DoSomething().Wait();
     return list;
}
public async Task<List<Test>> DoSomething()
{
     //do something
}

It will wait until MyFunction is completed, then return back to MyAjaxFunction.

Asherguru
  • 1,687
  • 1
  • 5
  • 10