简体   繁体   中英

make $.getJSON into a general purpose function

Since I'm using this type of call often I wish to make this reusable:

function getJSON(cmd){
   $.getJSON(cmd, function(data) {
   }).done(function(data) {
       return data;
   }).fail(function() { console.log('Server failed!') });
}

I hoped to use it like this:

function susbcribe(id){
   var cmd = 'subscribe.php?='+id;
   var obj = getJSON(cmd);
   console.log(obj);    
}

But javascript runs console.log before the async json can even return anything to obj.

Just to be clear - i know i can execute code inside of .done(), but because I use this often I wish to forgo rewriting the same function over and over.

So the question is: is there a way to make js stop and wait for getJSON to finish and return something to obj ?

As things currently stand, you will have to at least write the done function every time. You can't escape callback hell by pretending it doesn't exist.

There are ways to avoid some of it by using promises cleverly, but for simple things, this is pretty much as simple as it gets. Until we get support for generators/iterators some time in 2025.

You could set the fail function as a global "ajax event" handler to avoid having to type error handling every time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM