Home Return async variable or true/false to use in other function
Reply: 1

Return async variable or true/false to use in other function

Meules
1#
Meules Published in 2018-01-11 17:53:19Z

This question already has an answer here:

  • How do I return the response from an asynchronous call? 26 answers

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.

guest271314
2#
guest271314 Reply to 2018-01-11 17:57:51Z

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
    }
}); 
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.32891 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO