如何用蓝鸟包装承诺
how to wrap a promise with bluebird
我将 bluebird 用于 promise,但也使用 returns 非 bluebird promise 的库。我想使用 .asCallback
。我尝试使用 Promise.resolve
来包装它,这是我在网上其他地方找到的,但它隐藏了承诺链中的错误。在代码中,如果我取出 then/catch
它会解决而不是从客户端调用中抛出错误,即使发生了错误。
除了使用 new Promise(resolve,reject)
创建一个新的承诺之外,这是一个显而易见的解决方案,是否有更好的方法将其转换为蓝鸟承诺,将任何错误传播到原始承诺链?
module.exports.count = function(params, done){
var promise = client.count({
"index": config.search.index + "_" + params.index
}).then(function(response){
logger.debug(response);
}).catch(function(e){
logger.error(e);
});
return Promise.resolve(promise).asCallback(done);
Promise.resolve
传播错误。您的问题似乎是 catch
在它们到达 resolve
之前处理了它们。你应该做
function count(params, done){
return Promise.resolve(client.count({
"index": config.search.index + "_" + params.index
})).then(function(response){
logger.debug(response);
return response; // important!
}, function(e){
logger.error(e);
throw e; // important!
}).asCallback(done);
}
我将 bluebird 用于 promise,但也使用 returns 非 bluebird promise 的库。我想使用 .asCallback
。我尝试使用 Promise.resolve
来包装它,这是我在网上其他地方找到的,但它隐藏了承诺链中的错误。在代码中,如果我取出 then/catch
它会解决而不是从客户端调用中抛出错误,即使发生了错误。
除了使用 new Promise(resolve,reject)
创建一个新的承诺之外,这是一个显而易见的解决方案,是否有更好的方法将其转换为蓝鸟承诺,将任何错误传播到原始承诺链?
module.exports.count = function(params, done){
var promise = client.count({
"index": config.search.index + "_" + params.index
}).then(function(response){
logger.debug(response);
}).catch(function(e){
logger.error(e);
});
return Promise.resolve(promise).asCallback(done);
Promise.resolve
传播错误。您的问题似乎是 catch
在它们到达 resolve
之前处理了它们。你应该做
function count(params, done){
return Promise.resolve(client.count({
"index": config.search.index + "_" + params.index
})).then(function(response){
logger.debug(response);
return response; // important!
}, function(e){
logger.error(e);
throw e; // important!
}).asCallback(done);
}