2017-02-02 32 views
0

我使用bluebird作爲承諾,但也使用返回非藍鳥承諾的庫。我想使用.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); 
+0

你是什麼意思的「*它隱藏了諾言鏈中的錯誤*」? 'Promise.resolve'當然不會這樣做。然而你的catch()調用可能會。 – Bergi

回答

1

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); 
} 
+0

也許這是父母承諾鏈中的其他內容。我添加了catch來排除故障,所以我的代碼示例實際上很糟糕。讓我重新檢查。 –

+0

我認爲這只是我父母鏈處理程序中的錯誤。我仍在學習如何正確使用承諾... –