[英]Unhandled rejection in Bluebird
我有以下代碼。 當f2
沒有錯誤時,它工作正常。
如果存在錯誤,則會生成Unhandled rejection Error
。
重寫代碼以避免Unhandled rejection Error
並正確傳播以catch
f1
正確方法是什么?
let Bluebird = require('bluebird'),
mkdirp = Bluebird.promisify(require('mkdirp')),
request = Bluebird.promisify(require('request')),
writeFile = Bluebird.promisify(require('fs').writeFile);
function f1() {
.........
f2(path, fileName, options).then(.....).catch(....);
}
function f2(path, fileName, options) {
p = mkdirp(path).then(request(options).then(res => {
if (res[0].statusCode === 200) {
writeFile(fileName, res[0].body);
return res[0].body;
} else {
throw new Error(res[0].statusCode + ': ' + res[0].body);
}
}));
return p;
}
問題是您正在將諾言傳遞給f2
.then()
。 .then()
將忽略不是函數的所有內容,因此f2
真正返回的所有內容都是對mkdirp(this.path)
的承諾,由於mkdirp(this.path)
,這是一個大錯誤。 如果在request(options)
的then
處理程序中引發了錯誤,那么將沒有任何東西可以處理。
另外,您沒有做任何事情來處理writeFile
可能出現的錯誤。 如果調用writeFile
,則需要返回一個包含它的promise鏈,或者添加邏輯以在f2
處理它。
因為看起來您可以在此處並行運行mkdirp()
和request()
,但是您沒有使用mkdirp()
的結果, mkdirp()
我想這是一種方法:
function f2(path, fileName, options) {
var p = mkdirp(path).return(request(options)).then(res => {
if (res[0].statusCode === 200) {
return writeFile(fileName, res[0].body)
.return(res[0].body);
} else {
throw new Error(res[0].statusCode + ': ' + res[0].body);
}
});
return p;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.