【问题标题】:Implementation of chained es6 promises within a class在一个类中实现链式 es6 Promise
【发布时间】:2015-07-24 16:34:09
【问题描述】:

我对 es6 Promise 中 this 的上下文有点困惑。下面是一些使用Promise 处理异步函数的代码。

/**
* Generic recreation of apple photobooth on electron (javascript practice)
*/
class Photobooth {
  constructor(height=320, width=320) {
    this._height = 320;
    this._width = 320;
    this.video = video ? $(video) : $(document.createElement('video'));
  }
  getStream() {
    return new Promise(function (resolve, reject) {
      return navigator.webkitGetUserMedia({ video: true }, resolve, reject);
    });
  }
  streamTo(stream, element) {
    element.appendChild(self.video);
    var self = this;
    return new Promise(function (resolve, reject) {
      self.video.attr('src', window.URL.createObjectUrl(stream));
      self.video.on('loadedmetadata', function () {
        self.video.get(0);
        resolve();
      });
    });
  }
}

我想实现如下所示的链接。

Photobooth
  .getStream()
  .streamTo(document.body);

Lodash 具有与链接类似的功能。

// gets sorted scores for class.
_([
  { name: 'Jeff', scores: [0.78, 0.85] },
  { name: 'Jessica', scores: [0.84, 0.68] },
  { name: 'Tim', scores: [0.92, 0.67] }
])
  .pluck('scores')
  .flatten()
  .map(x => x * 100)
  .sortBy()
  .value();

如何在 javascript 中实现基于类的 Promise-chaining?

【问题讨论】:

  • 您需要使用then 显式处理resolved 事件。 lodash 示例没有使用承诺。
  • 您当前的实现将用作let inst = new Photobooth(); inst.getStream().then(stream => inst.streamTo(stream, document.body))。有理由不这样做吗?
  • this 和 promises 没有任何关系。

标签: javascript promise ecmascript-6 es6-promise


【解决方案1】:

我对 es6 Promise 中 this 的上下文有点困惑

promise 没有什么特别之处,this 一如既往地工作。使用 ES6,它确实简化了使用箭头函数进行承诺回调的事情。

我想实现链接

目前,您的函数确实返回了 Promise,尽管它与 then 链接。对于自定义链接,就像下划线一样,您必须将数据(在本例中为 Promise)包装在具有所需方法的自定义对象中。

在您的特定情况下,您可能根本不使用该 getStream 方法,这似乎是您的 PhotoBoth 实例的唯一目的,因此您可以将其直接放入构造函数中。我会做的

class Photobooth {
  constructor(video=document.createElement('video'), height=320, width=320) {
    this._height = 320;
    this._width = 320;
    this.video = $(video);
    this.initStream()
  }
  initStream() {
    this.stream = new Promise((resolve, reject) =>
      navigator.webkitGetUserMedia({video: true}, resolve, reject);
    );
  }
  streamTo(element) {
    this.video.appendTo(element);
    return this.stream.then((stream) => new Promise((resolve, reject) => {
      this.video.prop('src', window.URL.createObjectUrl(stream));
      this.video.on('loadedmetadata', function(e) {
        resolve(this);
      });
    }), (err) => {
      $(element).text("Failed to get stream");
      throw err;
    });
  }
}

【讨论】:

    猜你喜欢
    • 2016-12-12
    • 2015-12-24
    • 2017-05-24
    • 2018-03-16
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 2015-09-28
    相关资源
    最近更新 更多