我想創建一個函數,該函數返回一個承諾,如果有內容拋出錯誤,則返回承諾拒絕。使用拋出承諾
function promiseFunc(options) {
return new Promise(() => {
return options;
});
}
function myfunc(options) {
return new Promise(() => {
if (!options) throw new Error("missing options");
return promiseFunc(options).then((result) => {
if (result.throwerr) throw new Error("thrown on purpose");
return result.value;
});
});
};
我的測試如下:
const myfunc = require("./myfunc");
describe('myfunc',() => {
it('should fail without options',() => {
return myfunc()
.then((result) => { throw new Error(result) }, (err) => {
console.log("test #1 result:", err.message === "missing options");
});
});
it('should fail on options.throwerr',() => {
return myfunc({throwerr: true})
.then((result) => {}, (err) => {
console.log("test #2 result:", err.message === "thrown on purpose");
});
});
it('should return options.value',() => {
return myfunc({value: "some result", throwerr: false})
.then((result) => {
console.log("test #3 result:", result === "some result");
}, (err) => {});
});
});
第一次測試通過,但第二和第三失敗。
日誌#2甚至沒有運行,所以我認爲「故意拋出」會弄亂某些東西,因此我創建了測試#3,在那裏我不扔任何東西,但仍然失敗。 我錯過了什麼?
解決方案:
function promiseFunc(options) {
return new Promise(resolve => {
return resolve(options);
});
}
function myfunc(options) {
return new Promise((resolve, reject) => {
if (!options) throw new Error("missing options");
return promiseFunc(options).then(result => {
if (result.throwerr) throw new Error("thrown on purpose");
return resolve(result.value);
}).catch(err => {
return reject(err);
});
});
};
避免['Promise' constructor antipattern](http://stackoverflow.com/q/23803743/1048572)! – Bergi