在Python中,我不时会看到块:
try:
try_this(whatever)
except SomeException as exception:
#Handle exception
else:
return something
Run Code Online (Sandbox Code Playgroud)
try-except-else存在的原因是什么?
我不喜欢那种编程,因为它使用异常来执行流控制.但是,如果它包含在语言中,那么必须有充分的理由,不是吗?
我的理解是,异常不是错误,它们只应用于特殊情况(例如我尝试将文件写入磁盘,没有更多空间,或者我没有权限),而不是流程控制.
通常我将异常处理为:
something = some_default_value
try:
something = try_this(whatever)
except SomeException as exception:
#Handle exception
finally:
return something
Run Code Online (Sandbox Code Playgroud)
或者如果我真的不想在发生异常时返回任何内容,那么:
try:
something = try_this(whatever)
return something
except SomeException as exception:
#Handle exception
Run Code Online (Sandbox Code Playgroud) 我仍然是相当新的承诺,目前正在使用蓝鸟,但我有一个场景,我不太确定如何最好地处理它.
例如,我在快递应用程序中有一个承诺链,如下所示:
repository.Query(getAccountByIdQuery)
.catch(function(error){
res.status(404).send({ error: "No account found with this Id" });
})
.then(convertDocumentToModel)
.then(verifyOldPassword)
.catch(function(error) {
res.status(406).send({ OldPassword: error });
})
.then(changePassword)
.then(function(){
res.status(200).send();
})
.catch(function(error){
console.log(error);
res.status(500).send({ error: "Unable to change password" });
});
Run Code Online (Sandbox Code Playgroud)
所以我追求的行为是:
所以,目前抓到似乎没有停止的链接,这是有道理的,所以我想知道如果有,我以某种方式迫使链停在基于错误的某一点的方式,或是否有更好的办法构造它以获得某种形式的分支行为,就像有一种情况一样if X do Y else Z.
任何帮助都会很棒.
以下2个代码有什么区别吗?
myPromise.then(function() {
console.log('success');
}).catch(function() {
console.log('error');
});
myPromise.then(function() {
console.log('success');
}, function() {
console.log('error');
});
Run Code Online (Sandbox Code Playgroud)
我知道then并catch通过回调中的值返回返回已解决或拒绝的新promise.但我看到网络上的2个代码,我很好奇2代码之间的真正差异.
我喜欢Async/Await在Typescript等中提供的新功能的平坦性.但是,我不确定我喜欢这样一个事实,即我必须await在try...catch块的外部声明变量才能在以后使用它.像这样:
let createdUser
try {
createdUser = await this.User.create(userInfo)
} catch (error) {
console.error(error)
}
console.log(createdUser)
// business
// logic
// goes
// here
Run Code Online (Sandbox Code Playgroud)
如果我错了,请纠正我,但似乎最好不要在机构中放置多行业务逻辑try,所以我只留下createdUser在块外声明,在块中分配它的替代方案,以及然后用它.
在这种情况下,最佳做法是什么?
在尝试捕获承诺拒绝时,我在IE8上遇到了一个奇怪的错误(基本ngResource调用返回的承诺):
此代码使用.then(success, fail)语法:
promise.then(function(response) {
// success
},
function(response) {
// error
});
Run Code Online (Sandbox Code Playgroud)
但这个失败的.then(success).catch(fail)语法:
promise.then(function(response) {
// success
})
.catch(function(response) {
// error
});
Run Code Online (Sandbox Code Playgroud)
并且指向该.catch()行的IE错误是:
预期的标识符
难道我做错了什么 ?有人重现了吗?或者由于受限制的关键字,它是一个常见的IE8?
谢谢
internet-explorer internet-explorer-8 promise angularjs angular-promise
在下面的代码片段error 1,并success 2会被记录.如果原始延迟被拒绝,我怎样才能传播被调用的错误回调而不是被调用的成功回调.
angular.module("Foo", []);
angular
.module("Foo")
.controller("Bar", function ($q) {
var deferred = $q.defer();
deferred.reject();
deferred.promise
.then(
/*success*/function () { console.log("success 1"); },
/*error*/function () { console.log("error 1"); })
.then(
/*success*/function () { console.log("success 2"); },
/*error*/function () { console.log("error 2"); });
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="Foo">
<div ng-controller="Bar"></div>
</div>Run Code Online (Sandbox Code Playgroud)
所有:
我对JS Promise很陌生,在Promise链接方面有一个令人困惑的地方,比如说我有一个像以下链接的承诺:
var p = new Promise(function(res, rej){
})
.then(
function(data){
},
function(err){
})
.then(
function(data){
},
function(err){
})
.catch(
function(err){
})
Run Code Online (Sandbox Code Playgroud)
让我困惑的是:
then?谢谢
如何在以后检索承诺的结果?在测试中,我在发送进一步请求之前检索电子邮件:
const email = await get_email();
assert.equal(email.subject, 'foobar');
await send_request1();
await send_request2();
Run Code Online (Sandbox Code Playgroud)
如何在慢速邮件检索过程中发送请求?
起初,我考虑过稍后等待电子邮件:
// This code is wrong - do not copy!
const email_promise = get_email();
await send_request1();
await send_request2();
const email = await email_promise;
assert.equal(email.subject, 'foobar');
Run Code Online (Sandbox Code Playgroud)
如果get_email()成功,这可以工作,但如果get_email()在相应的之前失败则失败await,并且完全合理UnhandledPromiseRejectionWarning.
当然,我可以使用Promise.all,像这样:
await Promise.all([
async () => {
const email = await get_email();
assert.equal(email.subject, 'foobar');
},
async () => {
await send_request1();
await send_request2();
},
]);
Run Code Online (Sandbox Code Playgroud)
然而,它使代码更难阅读(它看起来更像是基于回调的编程),尤其是在以后的请求实际上依赖于电子邮件,或者有一些嵌套回事.是否可以在以后存储承诺的结果/例外await?
如果需要,这里有一个带有模拟 …
短篇小说:
谈到Promises/A +,拒绝承诺的正确方法是什么 - 抛出错误?但如果我错过了catch- 我的整个应用程序将会爆炸!
如何使用promisify它有什么好处(也许你需要阅读更长的版本)?
是.then(success, fail)真正的反模式,我应该使用.then(success).catch(error)?
更长的版本,被描述为现实生活中的问题(希望有人阅读):
我有一个使用Bluebird(A + Promise实现库)的库,用于从数据库中获取数据(谈论Sequelize).每个查询都返回一个结果,但有时候它是空的(试图选择一些东西,但没有任何查询).承诺进入result函数,因为没有错误的原因(没有结果不是错误).例:
Entity.find(1).then(function(result) {
// always ending here, despite result is {}
}).catch(function(error) {
// never ends here
});
Run Code Online (Sandbox Code Playgroud)
我想包装它并检查结果是否为空(在我的代码中无法检查到这一点).我这样做了:
function findFirst() {
return Entity.find(1).then(function(result) {
if (result) { // add proper checks if needed
return result; // will invoke the success function
} else {
// I WANT …Run Code Online (Sandbox Code Playgroud) 这两个陈述之间究竟有什么区别?
funcThatReturnsAPromise()
.then(() => { /* success */ })
.catch(() => { /* fail */ });
funcThatReturnsAPromise()
.then(() => { /* success */ }, () => { /* fail */ });
Run Code Online (Sandbox Code Playgroud) promise ×8
javascript ×7
node.js ×3
angularjs ×2
async-await ×2
bluebird ×2
try-catch ×2
chain ×1
es6-promise ×1
exception ×1
python ×1