[英]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.