JavaScript模式用于处理诺言



我时不时地遇到了这一点:

return somethingThatReturnsAPromise()
  .then((response) => {
    soSomethingg(); // Eg; update the UI
    return response;
   });

现在,我正在寻找没有期望归还任何东西的东西,如果我忘记了这一点,不会改变承诺链:

return somethingThatReturnsAPromise()
  .whatImLookingFor((response) => {
    doSomething(); // Eg; update the UI
   })
   .then((response) => {
     // and this one should still be able to access response
   });

也许这违背了承诺的想法,但是对我来说,这有点不方便,因为我无法通过任意功能。

一个想法是构成一个函数:

const sideEffect = (callback) => {
  return (response) => {
    callback(response);
    return response;
  };
};

我可以用作

return somethingThatReturnsAPromise()
  .then(sideEffect(doSomething));

但是我更喜欢某些东西而不是then有类似的东西吗?

注意:我正在使用Angular 1.x,所以我需要类似的东西。

我会假设您不是真正编写.then().then(),因为您可以将其倒入一个.then中,但是您的担心实际上是要返回诺言,并让某些外部代码添加另一个外部代码then到链条。在这种情况下,这样做:

let p = somethingThatReturnsAPromise();
p.then(() => doSomething());
return p;

这使呼叫者可以将其他then s连接到原始承诺,而不是将.then链接起来,从而接收原始承诺的价值。这被称为分支 Promise链。

也许这违背了承诺的想法

略微,承诺链是管道,then处理程序在每个阶段都会改变事物。但是要通过不变的值是完全有效的。

一个想法是构成一个函数:

的确,想到的第一件事,以及我如何做。

但是我更喜欢某些东西,而不是then有类似的东西吗?

没有。您可以将其添加到Promise.prototype中,以将其添加到您自己的项目(我不会在库中)。或者,您可以给您一个Promise子类并在此处添加。

带有承诺的Sublass,您会做类似的事情:

return MyPromise.resolve(somethingThatReturnsAPromise())
  .thenSide(soSomethingg); // Eg; update the UI

... thenSide是您的方法是 then,但是将原始值返回不变,例如:

class MyPromise extends Promise {
    thenSide(callback) {
        this.then(callback);
        return this;
    }
}

class MyPromise extends Promise {
    thenSide(callback) {
        this.then(callback);
        return MyPromise.resolve(this);
    }
}

...取决于您是否对thenSide返回相同的诺言感到不安(因为then总是返回新的诺言)。

据我所知(我可能错了)"通过"副作用的包装方法是一种做您想要的惯用方法。

另外(如果您在多个位置需要相同的 response),则可以在遇到这种情况时分解承诺链。

最新更新