2011-03-02 97 views
0

我无法学习使用新的jQuery Deferred。jquery推迟

做了一个ajax调用,我想返回ajax调用的数据。

checkIDExists = function(id){ 
    var exists = false; 
    $.ajax({ 
     data: { 
      method: "idExists", 
      id: id 
     }, 
     success: function(data){ 
       if(data == 'true'){ 
        exists = true; 
       } 
     } 
    }).done(function(){ 
     return exists; 
    }).fail(function(){ 
     return false; 
    }); 
}; 

我知道问题进来时,我试图返回的东西里面的()完成或失败()不返回它的checkIdExists()函数的功能。我如何解决这个问题?

回答

2

Ajax本身异步工作,所以函数checkIDExists先完成,然后ajax调用返回来自服务器的数据。

在你的情况下,我不会依赖checkIDExists函数的返回值,但我会覆盖函数使用CPS的方法。

4

由劳合社的声明是正确的,据我知道,但我不认为这是正是你要找的答案,这是我的尝试:

首先,与延迟承诺的唯一合理的事情工作时期望并提供作为回报价值的承诺对象(因此Lloyd将您指向CPS)。

在那里你会通常这样做

/* Have some kind of callback for when ajax is done */ 

var myCompleteCallback = function(data){ 
    // whatever you want to do with your ajax call results 
} 

var myErrorCallback = function(){ 
    // handle the ajax error 
} 

/* Send the actual ajax request, and tell it to call MyCompleteCallback afterwards */ 

    $.ajax({ 
    url: '/foo/bar.xml' 
    data: {}, 
    success: myCompleteCallback, 
    error: 
    }); 

你会不喜欢这样的递延式implementaion:

/* Have some kind of callback for when promise is resolved is done */ 

var myCompleteCallback = function(data){ 
    // whatever you want to do with your ajax call results 
} 

var myErrorCallback = function(){ 
    // handle the ajax error 
} 

/* you could also do ajax.done().fail() but i think this reads better as an example */ 

var getsomething = $.ajax({ url: '/foo/bar.xml', data: {} }); 
getsomething.then(myCompleteCallback, myErrorCallback) 

所以你看,没有什么太多的神奇和不同关于它,除非你开始进入更复杂的例子。

请告诉我冷静一下吧,虽然(从前面的例子以下)...

var getVisitorInfo = function(){ 

    /* stash the user information ajax call promise */ 

    var fetchUserInfo = $.ajax({url:"/some/api/user.json"}) 

    /* stash the account information ajax call promise */ 

    var fetchAccountInfo = $.ajax({url:"/some/api/user.json"}) 

    /* trigger both calls and returns a promise that will resolve to both results */ 

    return $.when(fetchUserInfo, fetchAccountInfo) 
} 

/* Usage: */ 

getVisitorInfo().done(function(userJSON, accountJSON){ 
    // manipulate your data/ui/and whatnot 
}).fail(function(failure1,failure2){ 
    // redirect to login or whatever 
}) 

希望这有助于。我建议看看各种延迟/承诺实现,以更好地理解这一切。真正帮助我的是玩Kris Kowal's Q图书馆(以及他提供的高质量自述文件)并在CommonJS wiki上阅读。而克里斯也给了一个talk on the topic back in 2010