javascript – 链接承诺并保留`this`
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 链接承诺并保留`this`,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2636字,纯文字阅读大概需要4分钟。
内容图文
我有一个点击处理程序,需要一个接一个地进行几个异步调用.我选择使用promises来构造这些调用(准确地说是RSVP).
下面,您可以在控制器内看到clickA处理程序(它是一个Ember应用程序,但问题是更一般的,我认为):
App.SomeController = Ember.Controller.extend({
actions: {
clickA: function() {
var self = this;
function startProcess() {
return makeAjaxCall(url, {
'foo': self.get('foo')
});
}
function continueProcess(response) {
return makeAjaxCall(url, {
'bar': self.get('bar')
});
}
function finishProcess(response) {
return new Ember.RSVP.Promise(...);
}
...
startProcess()
.then(continueProcess)
.then(finishProcess)
.catch(errorHandler);
}
}
});
它看起来很棒,但现在我必须添加第二个重复使用某些步骤的操作.
由于每个内部函数都需要从控制器访问属性,因此一种解决方案是使它们成为控制器的方法:
App.SomeController = Ember.Controller.extend({
startProcess: function() {
return makeAjaxCall(url, {
'foo': this.get('foo')
});
},
continueProcess: function(response) {
return makeAjaxCall(url, {
'bar': this.get('bar')
});
},
finishProcess: function(response) {
return new Ember.RSVP.Promise(...);
},
actions: {
clickA: function() {
this.startProcess()
.then(jQuery.proxy(this, 'continueProcess'))
.then(jQuery.proxy(this, 'finishProcess'))
.catch(jQuery.proxy(this, 'errorHandler'));
},
clickB: function() {
this.startProcess()
.then(jQuery.proxy(this, 'doSomethingElse'))
.catch(jQuery.proxy(this, 'errorHandler'));
}
}
});
所以,我的问题是:有更好的方法吗?我可以以某种方式摆脱所有jQuery.proxy()调用吗?
解决方法:
解决方案是使用更好的promise库.
Bluebird有一个bind函数,它允许你将一个上下文绑定到整个promise链(你传递给then或catch或最后用这个上下文调用的所有函数).
这是一篇关于使用绑定承诺的文章(我写的),就像你想保留一个控制器/资源一样:Using bound promises to ease database querying in node.js
我像这样建立我的承诺:
// returns a promise bound to a connection, available to issue queries
// The connection must be released using off
exports.on = function(val){
var con = new Con(), resolver = Promise.defer();
pool.connect(function(err, client, done){
if (err) {
resolver.reject(err);
} else {
// the instance of Con embeds the connection
// and the releasing function
con.client = client;
con.done = done;
// val is passed as value in the resolution so that it's available
// in the next step of the promise chain
resolver.resolve(val);
}
});
// the promise is bound to the Con instance and returned
return resolver.promise.bind(con);
}
这允许我这样做:
db.on(userId) // get a connection from the pool
.then(db.getUser) // use it to issue an asynchronous query
.then(function(user){ // then, with the result of the query
ui.showUser(user); // do something
}).finally(db.off); // and return the connection to the pool
内容总结
以上是互联网集市为您收集整理的javascript – 链接承诺并保留`this`全部内容,希望文章能够帮你解决javascript – 链接承诺并保留`this`所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。