【发布时间】:2021-06-12 03:39:57
【问题描述】:
当执行这个程序时
const somePromise = Promise.reject("Shouldn't see this");
function f1() {
console.log("Hello World");
}
f1();
产生以下输出
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 创建一个默认值,以帮助对函数进行类型检查并避免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 不会为空来解决这个问题,但我希望有更多内在的方法来处理这个问题。
【问题讨论】:
标签: javascript node.js typescript promise