这两种语法有什么区别 [英] What is the difference between these two syntax
问题描述
如果我有
promise = userService.updateUser($stateParams.userId, req);承诺.然后(功能(用户){logger.logSuccess('更新用户');$scope.resetForm();WizardHandler.wizard().goTo(0);返回用户;},功能(错误){logger.logError('Ups 发生错误');console.error('错误更新用户:' + error);});承诺.然后(功能(用户){_.each(uploader.getNotUploadedItems(), function(item) {返回 item.formData.push({id:user.id});});});
然后,如果 updateUser 失败,将显示日志,然后第二个 then
将不会执行,但是如果我有
promise = userService.updateUser($stateParams.userId, req).then(功能(用户){logger.logSuccess('更新用户');$scope.resetForm();WizardHandler.wizard().goTo(0);返回用户;},功能(错误){logger.logError('Ups 发生错误');console.error('错误更新用户:' + error);});承诺.然后(功能(用户){_.each(uploader.getNotUploadedItems(), function(item) {返回 item.formData.push({id:user.id});});});
然后将执行第二个
我不知道为什么,我的意思是这不就是常规链接吗?
如果 updateUser 失败,将显示日志,然后第二个将不会执行
是的,因为您正在分支:
成功: - logSuccessAndResetForm()|- makeNewFormData()更新用户()--+承诺|错误 - logError()
<块引用>
但是当使用常规链接时,将执行第二个链
是的,当然.您的错误处理程序处理错误,promise
用返回值实现.
成功: - logSuccessAndResetForm() 成功: - makeNewFormData()|\ |updateUser() --+ >- 承诺 --+|/|错误 - logError() ´ 错误:(无)
另请参阅此答案,了解类似代码的更漂亮的控制流程图.
If i have
promise = userService.updateUser($stateParams.userId, req);
promise.then(
function(user) {
logger.logSuccess('Updated user');
$scope.resetForm();
WizardHandler.wizard().goTo(0);
return user;
},
function(error) {
logger.logError('Ups an error has occurred');
console.error('error updating user: ' + error);
}
);
promise.then(function(user) {
_.each(uploader.getNotUploadedItems(), function(item) {
return item.formData.push({
id: user.id
});
});
});
Then if the updateUser fails the log will be shown and then second then
will not be executed however if i have
promise = userService.updateUser($stateParams.userId, req).then(
function(user) {
logger.logSuccess('Updated user');
$scope.resetForm();
WizardHandler.wizard().goTo(0);
return user;
},
function(error) {
logger.logError('Ups an error has occurred');
console.error('error updating user: ' + error);
}
);
promise.then(function(user) {
_.each(uploader.getNotUploadedItems(), function(item) {
return item.formData.push({
id: user.id
});
});
});
The second then will be executed
I can't figure out why, i mean isn't this just regular chaining ?
if the updateUser fails the log will be shown and then second then will not be executed
Yes, because you're branching:
success: - logSuccessAndResetForm()
| - makeNewFormData()
updateUser() --+
promise |
error - logError()
but when using regular chaining the second chain will be executed
Yes, of course. Your error handler handles the error and the promise
is fulfilled with the return value.
success: - logSuccessAndResetForm() success: - makeNewFormData()
| \ |
updateUser() --+ >- promise --+
| / |
error - logError() ´ error: (nothing)
See also this answer for prettier control flow diagrams of similar code.
这篇关于这两种语法有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!