简体   繁体   English

使$ .getJSON成为通用函数

[英]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. 但是javascript会在异步json甚至可以将任何内容返回给obj之前运行console.log。

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. 只是要清楚-我知道我可以在.done()中执行代码,但是因为我经常使用它,所以我希望一遍又一遍地重写同一函数。

So the question is: is there a way to make js stop and wait for getJSON to finish and return something to obj ? 所以问题是:有没有一种方法可以使js停止并等待getJSON完成并向obj返回内容?

As things currently stand, you will have to at least write the done function every time. 按照目前的情况,您每次至少必须编写done函数。 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. 有一些方法可以通过巧妙地使用Promise来避免某些问题,但是对于简单的事情,这几乎和获得的结果一样简单。 Until we get support for generators/iterators some time in 2025. 在2025年之前,我们将获得发电机/迭代器的支持。

You could set the fail function as a global "ajax event" handler to avoid having to type error handling every time. 您可以将fail函数设置为全局“ ajax事件”处理程序,以避免每次都要键入错误处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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