我一直在关注bluebird promises以及promise.try与promise.resolve.then的不同之处在于抛出错误.首先使用promise.try的一些代码会引发同步错误
Promise.try(function() {
throw new Error('error');
}).catch(function(e) {
console.log(e);
});
Run Code Online (Sandbox Code Playgroud)
其次是一些在解析时抛出同步错误的代码
Promise.resolve().then(function() {
throw new Error('error');
}).catch(function(e) {
console.log(e);
});
Run Code Online (Sandbox Code Playgroud)
据我所知,他们的行为都是一样的.promise.try本质上是一种解决承诺的更清洁方式吗?
文档说promise.try:
将捕获其Promise .catch处理程序中的所有错误,而不必处理同步和异步异常流.
对于文档中给出的示例:
function getUserById(id) {
return Promise.try(function() {
if (typeof id !== "number") {
throw new Error("id must be a number");
}
return db.getUserById(id);
});
}
Run Code Online (Sandbox Code Playgroud)
如果抛出同步错误,将永远不会到达异步代码.如果你将上面的代码放在promise.resolve()中然后(..)会有什么区别吗?
任何有关promise.try的澄清/示例将不胜感激.
Ben*_*aum 11
添加到Bergi的答案:Promise.try是那些你不能使用的时间Promise.method.目标是避免将同步异常与拒绝同步的情况.
总之,应尽可能使用正在考虑Promise.try给Promise.method自旋.
var fn = Promise.method(function(){
// can throw or return here, and it'll behave correctly
});
Run Code Online (Sandbox Code Playgroud)
大致相同:
var fn = function(){
return Promise.try(function(){
// can throw or return here, and it'll behave correctly
});
});
Run Code Online (Sandbox Code Playgroud)
据我所知,他们的行为都是一样的.
是的,主要是.但是,在同步执行函数的.then(…)同时,将异步调用回调Promise.try.
promise.try本质上是一种解决承诺的更清洁方式吗?
是的,它确实提供了更清晰(更少混淆)的表示法.但它更像是一种优化,因为它Promise.resolve(undefined)首先不会产生任何优化.