如何包装需要异步调用的复杂 if-then 语句?
How do you wrap complex if-then statements that require async calls?
我是 bluebird promise 库的新手。而且我想知道是否有比我目前正在做的更好的方法来做 wrap complex if 然后分支语句可能需要也可能不需要异步调用。
我现在拥有的例子:
(function() {
if (a) {
return ModelA.findById(id);
} else if (b) {
return ModelB.findById(id);
} else if (c) {
return ModelC.findById(id);
} else {
return Promise.reject(new Error('a, b, or c must be specified'));
}
})()
.then(function(result) {
if(result == null) {
return new Error('Object not found')
}
result.removedBy = user.id;
result.removedWhen = new Date();
result.inactive = true;
return result.save();
})
我唯一要改变的就是把它放在 .then
:
Promise.resolve()
.then(function() {
if (a) return ModelA.findById(id);
if (b) return ModelB.findById(id);
if (c) return ModelC.findById(id);
throw new Error('a, b, or c must be specified');
})
.then(function(result) {
if (!result) {
return new Error('Object not found');
}
result.removedBy = user.id;
result.removedWhen = new Date();
result.inactive = true;
return result.save();
})
.catch(e => console.error(e));
这具有更好的错误处理特性:您不必担心异常和拒绝,潜在的编码错误与其他错误的处理方式相同。
在 .then
中还有一个额外的好处,那就是不用担心总是返回一个 promise(因为任何返回的东西都会自动包装在一个 promise 中),一个很好的不变式,也更具可读性。
我是 bluebird promise 库的新手。而且我想知道是否有比我目前正在做的更好的方法来做 wrap complex if 然后分支语句可能需要也可能不需要异步调用。
我现在拥有的例子:
(function() {
if (a) {
return ModelA.findById(id);
} else if (b) {
return ModelB.findById(id);
} else if (c) {
return ModelC.findById(id);
} else {
return Promise.reject(new Error('a, b, or c must be specified'));
}
})()
.then(function(result) {
if(result == null) {
return new Error('Object not found')
}
result.removedBy = user.id;
result.removedWhen = new Date();
result.inactive = true;
return result.save();
})
我唯一要改变的就是把它放在 .then
:
Promise.resolve()
.then(function() {
if (a) return ModelA.findById(id);
if (b) return ModelB.findById(id);
if (c) return ModelC.findById(id);
throw new Error('a, b, or c must be specified');
})
.then(function(result) {
if (!result) {
return new Error('Object not found');
}
result.removedBy = user.id;
result.removedWhen = new Date();
result.inactive = true;
return result.save();
})
.catch(e => console.error(e));
这具有更好的错误处理特性:您不必担心异常和拒绝,潜在的编码错误与其他错误的处理方式相同。
在 .then
中还有一个额外的好处,那就是不用担心总是返回一个 promise(因为任何返回的东西都会自动包装在一个 promise 中),一个很好的不变式,也更具可读性。