[英]Promise created with Promise.reject() gets called immediately
執行此程序時
const somePromise = Promise.reject("Shouldn't see this");
function f1() {
console.log("Hello World");
}
f1();
生產以下output
Hello World
(node:23636) UnhandledPromiseRejectionWarning: Shouldn't see this
(node:23636) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:23636) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
為什么 Promise 被執行?
這是否意味着使用 Promise.reject (或resolve
該問題)創建的 Promise 將始終在調用塊中創建后的某個時間點執行?
有沒有辦法為 Promise 創建一個默認值,以幫助對 function 進行類型檢查,並避免Variable 'f2Promise' is used before being assigned.
警告,如下例所示:
function f2() {
let f2Promise: Promise<any>; // = Promise.reject("This is the default rejection");
const firstArg = undefined;
someFuncWithCallback(firstArg, (cbArg) => {
console.log("In callback");
f2Promise = someAsyncFunc(cbArg)
.then((val) => {
return val;
})
.catch((err) => {
return Promise.reject(`Error because of issue in someAsyncFunc with val: ${err}`);
});
});
return f2Promise;
}
我知道我可以通過斷言f2Promise
不會是 null 來解決這個問題,但我希望有更多內在的方法來處理這個問題。
承諾根本不會被“執行”。 promise 就像一個容器,用於存放以下操作的結果:
您創建了已被拒絕的 promise。
在您的代碼中,您從 promise 中發現了一個錯誤,並立即拋出一個新錯誤。 這不是必需的。 以下是您可能想要重寫該代碼的方式:
function f2() {
const firstArg = undefined;
return new Promise((res) => {
someFuncWithCallback(firstArg, (cbArg) => {
res(someAsyncFunc(cbArg));
});
});
}
就我個人而言,我通常更喜歡使用助手 function 來執行此操作:
const { promisify } from 'util';
const promisifedFunc = promisify(someFuncWithCallback);
function f2() {
const firstArg = undefined;
return promisifiedFunc(firstArg)
.then(cbArg => someAsyncFunc(cbArg);
}
一些核心思想是這兩個是相同的:
return someAsyncOp().then( res => {
return res;
}
// Behaves the same as:
return someAsyncOp();
這三個也或多或少相同(這里有更多細微差別)。
return someAsyncOp()
.catch(err => {
return Promise.reject('Message');
});
// And
return someAsyncOp()
.catch(err => {
throw new Error('Message');
});
// And
return someAsyncOp();
這三個之間的區別是“拋出什么”。 因此,如果您明確想要捕獲一個錯誤只是為了拋出一個新錯誤,您可能需要中間選項。 如果您不關心引發了什么錯誤,並且只想確保如果內部 promise 失敗,那么外部 promise 也會失敗,只是不要抓住。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.