简体   繁体   English

使用 Promise.reject() 创建的 Promise 会立即被调用

[英]Promise created with Promise.reject() gets called immediately

When executing this program执行此程序时

const somePromise = Promise.reject("Shouldn't see this");

function f1() {
    console.log("Hello World");
}
f1();

The following output is produced生产以下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.

Why is the Promise getting executed?为什么 Promise 被执行?

Does this mean that a Promise created with Promise.reject (or resolve for that matter) will always get executed at some point after creation within a calling block?这是否意味着使用 Promise.reject (或resolve该问题)创建的 Promise 将始终在调用块中创建后的某个时间点执行?

And is there a way to create a default value for a Promise to assist in type checking of the function and to avoid Variable 'f2Promise' is used before being assigned.有没有办法为 Promise 创建一个默认值,以帮助对 function 进行类型检查,并避免Variable 'f2Promise' is used before being assigned. warnings, like the example below:警告,如下例所示:

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;
}

I know that I could possible to work around this issue, by asserting the f2Promise will not be null, but I would hope for more intrinsic ways to handle this.我知道我可以通过断言f2Promise不会是 null 来解决这个问题,但我希望有更多内在的方法来处理这个问题。

Promises don't get 'executed' at all.承诺根本不会被“执行”。 A promise is like a container for the result of an operation that's either: promise 就像一个容器,用于存放以下操作的结果:

  1. Pending待办的
  2. Rejected被拒绝
  3. Resolved解决

You created promise that's already rejected.您创建了已被拒绝的 promise。

In your code you are catching an error from a promise, and immediately throw a new one.在您的代码中,您从 promise 中发现了一个错误,并立即抛出一个新错误。 This isn't needed.这不是必需的。 Here's how you might want to rewrite that code:以下是您可能想要重写该代码的方式:

function f2() {
  const firstArg = undefined;
  return new Promise((res) => {
    someFuncWithCallback(firstArg, (cbArg) => {
      res(someAsyncFunc(cbArg));
    });
  });
}

Personally I prefer usually doing this with a helper function:就我个人而言,我通常更喜欢使用助手 function 来执行此操作:

const { promisify } from 'util';

const promisifedFunc = promisify(someFuncWithCallback);

function f2() {
  const firstArg = undefined;
  return promisifiedFunc(firstArg)
    .then(cbArg => someAsyncFunc(cbArg);
}

Some core ideas is that these two are the same:一些核心思想是这两个是相同的:

return someAsyncOp().then( res => {
  return res;
}

// Behaves the same as:

return someAsyncOp();

And these 3 are also more or less the same (there's more nuance here).这三个也或多或少相同(这里有更多细微差别)。

return someAsyncOp()
  .catch(err => {
    return Promise.reject('Message');
  });

// And

return someAsyncOp()
  .catch(err => {
    throw new Error('Message');
  });

// And

return someAsyncOp();

The difference between these 3 is 'what is thrown'.这三个之间的区别是“抛出什么”。 So if you explicitly want to catch an error just to throw a new one, you probably want the middle option.因此,如果您明确想要捕获一个错误只是为了抛出一个新错误,您可能需要中间选项。 If you don't care about what error is thrown and you just want to make sure that if the inner promise fails, the outer promise fails too just don't catch.如果您不关心引发了什么错误,并且只想确保如果内部 promise 失败,那么外部 promise 也会失败,只是不要抓住。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM