结合诺言和链接 [英] Combining promises and chaining

查看:75
本文介绍了结合诺言和链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在仍然支持链接的同时,是否存在用于利用Promise的良好设计模式?例如,假设我们有类似的东西:

Is there a good design pattern for utilizing promises, while still supporting chaining? For example, let's say that we have something like:

function Foobar() {
  this.foo = function() {
    console.log('foo');
    return this;
  };

  this.bar = function () {
    console.log('bar');
    return this;
  };
}

var foobar = new Foobar();
foobar.foo().bar();

如果相反,我们更改了使用诺言的方法,例如

If instead we change the methods to use promises, e.g.

function Foobar() {
  this.foo = function() {
    var self = this;
    return new Promise(function (resolve, reject) {
      console.log('foo');
      resolve(self);
    });
  };
  ...
}

是否有做某事的好方法:

Is there a good way to do something like:

var foobar = new Foobar();
foobar.foo().bar().then(function () {
  // do something
});

推荐答案

如果相反,我们更改了使用诺言的方法,例如

If instead we change the methods to use promises, e.g.

this.foo = function() {
  var self = this;
  return new Promise(function (resolve, reject) {
    …
    resolve(self);
  });
};

我建议不要这样做.这只是麻烦.如果您的实例(或它的修改)是计算的结果,那么在计算期间对象的状态是什么(我假设您使用OOP封装状态)?如果从事件循环的另一个进程(线程)调用此(或任何其他)方法,会发生什么情况?您必须沿着整个兔子洞走下去……

I would recommend not to do that. This just begs for trouble. If your instance (or: its modification) is the result of your computation, then what is the state of your object (I assume you use OOP to encapsulate state) during that computation? What happened if this (or any other) method is called from a different process (thread) turn of the event loop? You'd have to go down the entire rabbit hole…

尝试尽可能地使用函数式编程.

Try to use functional programming as far as you can.

是否有做某事的好方法:

Is there a good way to do something like:

new Foobar().foo().bar().then(function () {
  // do something
});

是的,但是每次调用后都必须使用.then:

Yes, but you'd have to use .then after every invocation:

new Foobar().foo().then(function(foobar) {
  return foobar.bar();
}).then(function(barresult) {
  // do something
});

Bluebird库(与其他一些库一样)甚至具有针对该

The Bluebird library (as do some others) even has a utility function for that .call(). So you'd do

new Foobar().foo().call("bar").then(function(barresult) {
  // do something
});

这篇关于结合诺言和链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆