我已经创建了一个原型,我有这个功能:
workRequests:
/**
* Works out all requests in the queue with
*/
function workRequests() {
/**
* Checks if queue of requests is empty
*/
if (this.queue.length == 0) {
this.setDone(true);
return;
}
/**
* Gets the next request
*/
var request = this.queue.shift();
request(function() {
workRequests();
});
},
函数commit
commit:
/**
* Executes all requests till there are no requests left
*/
function commit() {
console.log("committed");
/**
* Make sure the system is already committing all
*/
running = true;
this.workRequests();
},
关键是,我有一个名为queue
的数组,它可以存储任何函数。所以我想在queue
数组中添加许多函数,然后当我调用commit()
时,我想让它执行所有这些函数。但是,我不希望它一次执行所有这些,但我希望它们在队列中执行(等到每个完成,然后执行下一个)。
我已经使用递归来创建它,但我遇到了以下问题:
第一次调用workRequests
函数时,一切正常,但在调用workRequests()
的函数内部后,我会收到以下错误:
Uncaught TypeError: Cannot read property 'queue' of undefined
我不是javascript的专家所以我真的不明白幕后发生的事情会导致this
关键字失去它在workRequests()
的第一次调用中曾经相同的价值。
我称之为:
var reqs = new SyncRequests();
for(var i = 0; i < 5; i++) {
reqs.executeRequest(function(callback) {
$.ajax({
type: "POST",
async: true,
url: 'www.google.com',
data: {direction: 'up' },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (msg) {
callback();
},
error: function (err) {
callback();
}
});
});
}
reqs.commit();
非常感谢帮助解决错误,谢谢!
答案 0 :(得分:1)
您必须明确安排this
设置:
var request = this.queue.shift();
var self = this;
request(function() {
workRequests.call(self);
});
稍微简单一点:
var request = this.queue.shift();
request(workRequests.bind(this));
.bind()
方法返回一个调用您的函数的函数,以便将this
设置为给定值。