0

I created a Javascript function that returns a boolean value. One of the lines of code in the function invokes a REST call. I didn't realize that call was going to be asynchronous when I coded it. So, basically, the method always returns 'false' when I do something like:

if(isDataValid()) ...

I could move the actions in the calling function to the success function, but I was trying to create a reusable method. I'm using jQuery and Everest. I have not learned anything about Promises yet and I'm fairly new to callback programming.

Here's boiled down version of my method:

function isDataValid(){

    // Read data from Local Storage

    // Create object from data

    // Flag variable to capture result
    var isValid = null;

    restClient
        .read('/my/url', model)
        .done(function(response)
            {    
                // 'Good' response, set flag to true
                isValid = true;
            })
        .fail(function(response)
            {   
                // 'Bad' response, set flag to false
                isValid = false;
            });

    return isValid;
}

How should I make an async call and return true/false?

Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
Doug Dawson
  • 1,254
  • 2
  • 21
  • 37
  • You simply cannot. If any part of the stack is asynchronous, everything must be written with async in mind (either via callbacks or promises). You cannot call the function and expect to be able to get the response synchronously. – Felix Kling Oct 15 '17 at 00:11
  • Create your "reusable method" and invoke it from the success function passing `invalid` as a parameter. – jdigital Oct 15 '17 at 00:12

1 Answers1

0

Function should be marked as async in order for await to be used inside.

Since you didn't use response, I removed it. If you need response, then

var response = await restClient.read('/my/url/', model);

You should use try/catch to handle errors. Here is the end result:

async function isDataValid(){

   var isValid = null;

   try {
       await restClient.read('/my/url', model);
       isValid = true;
   } catch(err) {
       isValid = false;
   }

   return isValid;
}

In the end to call isDataValid you should also use await in front of the function call. So it will looks like that:

if(await isDataValid()) { ... }

Since await can be used only inside async functions, function where isDataValid is called should be also marked as async. This way you should update all the chain of function calls to be used with await.