0

First of all I've read this thread (especially this answer)about async calls and returns. However I still struggeling with my issue for a few days now!

I'm building a script to check if a postcode is available in an array. The answer should be true or false. However using that thread's answers still keeps returning undefined. I'm still learning so be gentle :)

What I've done is this:

function checkPostcode(pc_nr_check) {
 ...........
    $.getJSON(url+'?format=json', function(data){
    ........          
     var postcodeArray = postcodes
     var postcodeInArray = pc_nr_check

     if ($.inArray(postcodeInArray, postcodeArray) > -1){
         myCallback(true)
     } else {
         myCallback(false)
     }
  }); 
}
function myCallback(response) {
    var answer = response;
    return answer;
} // console.log this give true or false 

$('.custom-checkout').on('click', function(e){
    var is_available = myCallback();
    if(is_available){
      // show some stuff
     }
}); 

I just can't see why this is undefined. I also tried to set a global var answer and removed the return answer; from the myCallback function.

Any help greatly appreciated.

Meules
  • 1,349
  • 4
  • 24
  • 71
  • 2
    You can't return something from an async function, because the function runs after the original caller returns. It just makes no sense. – Barmar Jan 11 '18 at 17:55
  • This is explained in the question you linked to. If you didn't understand it there, we're not going to be able to do much better here. – Barmar Jan 11 '18 at 17:56
  • 1
    I don't understand the purpose of your `myCallback` function. It just returns whatever you send it. And in your code you either call it with an argument and ignore the response, or call it without an argument (which means it's going to return `undefined`). And nothing in your code calls the `checkPostcode` function in the first place. – David Jan 11 '18 at 17:56
  • When you understand how async functions work, what you're asking for is for the current function to return a value that won't be known until a future point in time... not really possible. – Erik Philips Jan 11 '18 at 17:57

1 Answers1

0

You can use async/await, return the Boolean from the original function call

function checkPostcode(pc_nr_check) {
 ...........
    return $.getJSON(url+'?format=json')
    .then(function(data) {
    ........          
     var postcodeArray = postcodes
     var postcodeInArray = pc_nr_check

     return $.inArray(postcodeInArray, postcodeArray) > -1
  }); 
}

$('.custom-checkout').on('click', async function(e){
    var is_available = await checkPostcode();
    if(is_available){
      // show some stuff
    }
}); 
guest271314
  • 1
  • 15
  • 104
  • 177