Sea*_*ndo 4 javascript node.js promise bluebird
我们知道,this下面是指window对象.我想知道的是我如何this在不诉诸var self=this;诡计的情况下传递我的背景.有任何想法吗?我尝试将.bind()添加到第9行的末尾,因此它可以读取,}).bind(this);但也不起作用.
有任何想法吗?
QueueService.prototype.FillCompanyQueue = function(companies) {
return Promise.map(companies, function (company_batch) {
var params = {
Entries: company_batch,
QueueUrl: Config.get("AWS-Queue.Company")
};
return this._sqs.sendMessageBatchAsync(params);
});
};
Run Code Online (Sandbox Code Playgroud)
编辑:我标记了它,但应该提到我正在使用Bluebird.
编辑:修正了一个错字.
你可以使用Bluebird的绑定功能:
QueueService.prototype.FillCompanyQueue = function(companies) {
return Promise.resolve(companies).bind(this).map(function(company_batch) {
var params = {
Entries: company_batch,
QueueUrl: Config.get("AWS-Queue.Company")
};
return this._sqs.sendMessageBatchAsync(params);
});
};
Run Code Online (Sandbox Code Playgroud)
如果在承诺链的延续中不需要外部上下文,我不确定它比"诉诸var self=this;诀窍" 要好得多.
当然,如果您使用的是ES6,您也可以使用箭头功能:
QueueService.prototype.FillCompanyQueue = function(companies) {
return Promise.map(companies, (company_batch) => {
var params = {
Entries: company_batch,
QueueUrl: Config.get("AWS-Queue.Company")
};
return this._sqs.sendMessageBatchAsync(params);
});
};
Run Code Online (Sandbox Code Playgroud)