简体   繁体   English

我必须履行我的JavaScript承诺吗?

[英]Do I have to fulfil my JavaScript promises?

In a Node.js environment if I do this: Node.js环境中,如果我这样做:

var doNoResolve = true;

function a() {
    return new Promise(resolve => {
        if (doNotResolve) {
            return
        }
        resolve(10);
    });
}

a().then(() => {
    // I don't want this getting fired
});

On an incoming request, is this a memory leak? 在传入的请求中,这是内存泄漏吗? If I was using a plain old callback everything would turn out just fine if I didn't execute whatever callback was supplied, but this feels like it might not be... the very name promise implies this is somewhat wrong. 如果我使用一个普通的旧回调,如果我没有执行任何回调,那么一切都会好起来,但这感觉就像它可能不是......这个名字承诺意味着这有点不对。

If I had to I could return a "fake promise" ( return { then: () => {} } ) inside function a() rather than a "real promise" if doNotResolve was true, but that feels a bit gross. 如果我必须,我可以在function a()返回一个“假承诺”( return { then: () => {} } ),如果doNotResolve为真,则返回“真正的承诺”,但这感觉有点严重。

The particular use-case is that of an isomorphic React.js application where I don't want HTTP requests actually getting made (but I do want my stores to update to a state that causes, say, a loading icon to appear). 特定的用例是一个同构的React.js应用程序,我不希望实际发出HTTP请求(但我确实希望我的商店更新到导致加载图标出现的状态)。

Why would you do that instead of rejecting? 你为什么要这样做而不是拒绝?

The benefit of promises is that they allow both resolving and rejecting, which: 承诺的好处是它们允许解析和拒绝,其中:

  1. Doesn't fire the then handler (unless you provide two callbacks, which is considered bad practice) 不会触发then处理程序(除非你提供两个回调,这被认为是不好的做法)
  2. Does fire the catch handler, which explicitly handles errors 触发catch处理程序,它显式处理错误
  3. Still fire the finally handler 仍然解雇finally处理程序

You can simply do: 你可以简单地做:

function a() {
    return new Promise((resolve, reject) => {
        if (doNotResolve) {
            reject(new Error('Oh noes!'));
        }
        resolve(10);
    });
}

Any good Promise implementation will give you a stacktrace from the location you called reject to help you debug async code, as well as calling any catch/finally handlers: 任何好的Promise实现都会从你调用reject的位置给你一个堆栈跟踪,以帮助你调试异步代码,以及调用任何catch / finally处理程序:

a().then(val => {
  console.log('Got data:', val);
}).catch(err => {
  console.error(err);
}).finally(() => {
  console.log('Done!');
});

Never rejecting or resolving a promise will, depending on your implementation, leave it on the stack of pending promises and very likely throw or log an error when your page unloads or the node promise exits. 永远拒绝或解决承诺将取决于您的实现,将其留在待处理的承诺堆栈中,并且很可能在您的页面卸载或节点承诺退出时抛出或记录错误。 I know Bluebird will complain if you've left any promises pending, since it typically indicates a bug within the async part of your code. 我知道Bluebird会抱怨你是否已经保留任何未决的承诺,因为它通常表示代码的异步部分中存在错误。

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

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