我编写的代码看起来像:
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构造函数反模式 ",这个代码有什么不好,为什么这被称为 …
Try-catch旨在帮助进行异常处理.这意味着它将以某种方式帮助我们的系统更加健壮:尝试从意外事件中恢复.
我们怀疑在执行和指令(发送消息)时可能会发生某些事情,因此它会被包含在try中.如果发生几乎意外的事情,我们可以做点什么:我们写下了捕获.我认为我们没有打电话来记录异常.我认为catch块意味着让我们有机会从错误中恢复.
现在,假设我们可以从错误中恢复,因为我们可以修复错误.重做是非常好的:
try{ some_instruction(); }
catch (NearlyUnexpectedException e){
fix_the_problem();
retry;
}
Run Code Online (Sandbox Code Playgroud)
这将很快落入永恒循环,但是假设fix_the_problem返回true,那么我们重试.鉴于Java中没有这样的东西,你将如何解决这个问题?解决这个问题的最佳设计代码是什么?
这就像一个哲学问题,因为我已经知道我所要求的并不是Java直接支持的.
编辑
代码为#1.继续重试,直到诺言解决(语言的任何改进社区等?)
Promise.retry = function(fn, times, delay) {
return new Promise(function(resolve, reject){
var error;
var attempt = function() {
if (times == 0) {
reject(error);
} else {
fn().then(resolve)
.catch(function(e){
times--;
error = e;
setTimeout(function(){attempt()}, delay);
});
}
};
attempt();
});
};
Run Code Online (Sandbox Code Playgroud)
使用
work.getStatus()
.then(function(result){ //retry, some glitch in the system
return Promise.retry(work.unpublish.bind(work, result), 10, 2000);
})
.then(function(){console.log('done')})
.catch(console.error);
Run Code Online (Sandbox Code Playgroud)
#2的代码继续重试,直到条件then以可重用的方式满足结果(条件是变化的).
work.publish()
.then(function(result){
return new Promise(function(resolve, reject){
var intervalId = setInterval(function(){
work.requestStatus(result).then(function(result2){
switch(result2.status) { …Run Code Online (Sandbox Code Playgroud) 我试图编写代码,使用Promise API重新连接到数据库并超时.
最后我最终做的是承诺在承诺中连接数据库,但我不确定这是否是最好的做事方式.我认为可能有一种方法可以使用原始的承诺来尝试连接到数据库,但我无法弄明白.
function connect(resolve) {
console.log('Connecting to db...');
MongoClient.connect(url, { promiseLibrary: Promise })
.then((db) => resolve(db))
.catch((err) => {
console.log('db connection failed!:\n', err);
if (retry++ < 3) {
console.log('Trying again...');
setTimeout(() => connect(resolve), 5000);
} else {
console.log('Retry limit reached!');
}
});
}
module.exports = new Promise(connect);
Run Code Online (Sandbox Code Playgroud)
我认为没有setTimeout阻挡就有可能,但我无法解决它.
我有这个异步块:
test().then(function(result){
// Success: Do something.
doSomething();
}).catch(function(error){
// Error: Handle the error, retry!
// How to re-run this whole block?
});Run Code Online (Sandbox Code Playgroud)
我可以跟踪的success和failed成果。但是,test().then().catch()如果我们失败了,是否可以重试整个链?并继续重试直到条件解决?
javascript ×4
promise ×4
node.js ×2
asynchronous ×1
bluebird ×1
es6-promise ×1
exception ×1
java ×1
q ×1
try-catch ×1