我想使用promises,但我有一个回调API,格式如下:
window.onload; // set to callback
...
window.onload = function() {
};
Run Code Online (Sandbox Code Playgroud)
function request(onChangeHandler) {
...
}
request(function() {
// change happened
...
});
Run Code Online (Sandbox Code Playgroud)
function getStuff(dat, callback) {
...
}
getStuff("dataParam", function(err, data) {
...
})
Run Code Online (Sandbox Code Playgroud)
API;
API.one(function(err, data) {
API.two(function(err, data2) {
API.three(function(err, data3) {
...
});
});
});
Run Code Online (Sandbox Code Playgroud)
我编写的代码看起来像:
function getStuffDone(param) { | function getStuffDone(param) {
var d = Q.defer(); /* or $q.defer */ | return new Promise(function(resolve, reject) {
// or = new $.Deferred() etc. | // using a promise constructor
myPromiseFn(param+1) | myPromiseFn(param+1)
.then(function(val) { /* or .done */ | .then(function(val) {
d.resolve(val); | resolve(val);
}).catch(function(err) { /* .fail */ | }).catch(function(err) {
d.reject(err); | reject(err);
}); | });
return d.promise; /* or promise() */ | });
} | }
Run Code Online (Sandbox Code Playgroud)
有人告诉我这个被称为" 延迟反模式 "或" Promise构造函数反模式 ",这个代码有什么不好,为什么这被称为 …
我看了一下bluebird promise FAQ,其中提到了这.then(success, fail)是一个反模式.我不太了解它对try和catch的解释.以下是什么问题?
some_promise_call()
.then(function(res) { logger.log(res) }, function(err) { logger.log(err) })
Run Code Online (Sandbox Code Playgroud)
似乎这个例子建议以下是正确的方法.
some_promise_call()
.then(function(res) { logger.log(res) })
.catch(function(err) { logger.log(err) })
Run Code Online (Sandbox Code Playgroud)
有什么不同?
我知道如何处理promises中的特定错误但我有时会看到如下代码片段:
somePromise.then(function(response){
otherAPI(JSON.parse(response));
});
Run Code Online (Sandbox Code Playgroud)
有时,我得到无效的JSON,这会在JSON.parse throws 时导致静默失败.一般来说,我必须记住.catch在我的代码中为每个承诺添加一个处理程序,当我不在时,我无法找到我忘记的地方.
如何在代码中找到这些被抑制的错误?