问题描述
现在,我在核心文件中使用promise.deferred.这使我可以在中心位置兑现承诺.我一直在读我可能正在使用反模式,我想了解为什么它不好.
Right now I use promise.deferred in a core file. This allows me to resolve promises at a central location. I've been reading that I may be using an anti-pattern and I want to understand why it is bad.
因此在我的 core.js 文件中,我具有以下功能:
so in my core.js file I have functions like this:
var getMyLocation = function(location) {
var promiseResolver = Promise.defer();
$.get('some/rest/api/' + location)
.then(function(reponse) {
promiseResolver.resolve(response);
)}
.catch(function(error) {
promiseResolver.reject(error);
});
return promiseResolver.promise;
}
然后在我的 getLocation.js 文件中,具有以下内容:
And then in my getLocation.js file I have the following:
var core = require('core');
var location = core.getMyLocation('Petersburg')
.then(function(response) {
// do something with data
}).catch(throw error);
阅读了Bluebird文档和许多有关延迟反模式的博客文章后,我想知道这种模式是否可行.我可以将其更改为以下内容:
After reading the Bluebird docs and many blog posts about the deferred anti-pattern I wonder if this pattern is practical. I could change this to the following:
core.js
var getMyLocation = function(location) {
var jqXHR = $.get('some/rest/api/' + location);
return Promise.resolve(jqXHR)
.catch(TimeoutError, CancellationError, function(e) {
jqXHR.abort();
// Don't swallow it
throw e;
});
getLocation.js
var location = core.getMyLocation('Petersburg')
.then(function(response) {
// do something
})
.catch(function(error) {
throw new Error();
});
我想让中央库使用jquery来处理xhr请求,而使用Bluebird来处理promise的最佳方法是什么,我感到困惑.
I guess I'm confused by what is the best way to have a central library that handles xhr requests using jquery for the calls, but Bluebird for the promises.
推荐答案
您可以调用 Promise.resolve
在jQuery thenable上并让Bluebird吸收它:
You can call Promise.resolve
on a jQuery thenable and have Bluebird assimilate it:
var res = Promise.resolve($.get(...)); // res is a bluebird Promise
您还可以直接在Bluebird链中返回jQuery Promise,并将其吸收.
You can also return jQuery promises directly inside a Bluebird chain and have it assimilate it.
myBluebirdApi().then(function(){
return $.get(...);
}).then(function(result){
// The jQuery thenable was assimilated
});
您的以下代码已结束,但是您无需抓住TimeoutError
,因为jQuery ajax不会抛出这些.至于捕捉取消错误.无论如何,这都是最佳做法,以防您需要取消请求.
Your code below is close, but you don't need to catch TimeoutError
since jQuery ajax won't throw those. As for catching cancellation error. This is best practice anyway for what you're doing if you ever expect to need to cancel the request.
这篇关于如何在没有延迟的Anit模式的情况下将jQuery $ .ajax调用转换为Bluebird Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!