Javascript 当任务完成或已完成时调用回调

Javascript 当任务完成或已完成时调用回调,javascript,jquery,ajax,events,asynchronous,Javascript,Jquery,Ajax,Events,Asynchronous,我有一个涉及异步任务的简单代码: // The NewsFeed Class function NewsFeed() { this.loadFeed = function() { $.ajax({ url: "http://www.example.com", success: function() { // doSomething here, and call onload.

我有一个涉及异步任务的简单代码:

// The NewsFeed Class

function NewsFeed() {

    this.loadFeed = function() {
        $.ajax({
            url: "http://www.example.com",
            success: function() {
                // doSomething here, and call onload.
            }
        });
    }

    // Need to implement onload here somehow
    this.onload = ?;

    this.loadFeed();
    return this;

}
NewsFeed.constructor = NewsFeed;



// In main JS file
var newsFeed = new NewsFeed();
$(function() {
    // do something
    newsFeed.onload = function() { // do something when news feed is loaded };
}
我的要求是,在这两种情况下都需要执行新闻提要的onload:

  • 如果loadFeed的ajax完成,请立即运行它
  • 如果loadFeed的ajax还没有完成,请运行它

确实不需要使用
new
构造函数当您不需要新实例时,您真正需要的是运行一个简单的ajax函数,如果缓存没有更改,则从缓存中获取结果

function newsFeed() {
   return $.ajax({
       url   : "http://www.example.com",
       cache : true // let the browser handle caching for you
   });
}


// In main JS file
$(function() {
    newsFeed().then(function() { 
        // do something when news feed is loaded 
    });
});

新的模式而不是回调是使用承诺 见:

使用jquery,您可以使用:

现在代码是:

函数NewsFeed(){
函数loadFeed(){
var deferred=$.deferred();
$.ajax({
url:“http://www.example.com",
成功:功能(数据){
延迟。解析(数据);
},
错误:函数(数据){
延迟。拒绝(数据);
}
});
延迟返回。承诺();
}
this.loadFeed=loadFeed;
归还这个;
}
NewsFeed.constructor=NewsFeed;
//在主JS文件中
var newsFeed=newnewsfeed();
newsFeed.loadFeed().done(函数(数据){
//数据加载成功
})
.失败(功能(数据){
//ajax请求失败
})
.always(函数(){
//最后:

});
this.loadFeed()将抛出一个错误。但不管怎样,听起来你在描述承诺的作用。完成后它将执行一个回调,如果您在完成后添加另一个回调,它将立即被调用并返回结果。谢谢,这是错误的。它应该是
this.loadFeed=function()
这是一种非常常见的反模式<代码>$。ajax
已返回承诺,无需创建新的承诺请参见