javascript - 在类中实现链式 es6 Promise

标签 javascript promise ecmascript-6 es6-promise

我对 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 链?

最佳答案

I'm a bit confused by the context of this in es6 promises

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

I want to implement chaining

目前,您的函数确实返回 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;
    });
  }
}

关于javascript - 在类中实现链式 es6 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31615573/

相关文章:

javascript - 突出显示句子中的单独关键字

javascript - 用于显示异步请求状态的 GUI 组件

javascript - 为什么不能通过 "data execution prevention"修复 Javascript shellcode 漏洞?

javascript - 在 Promise 构造函数范围之外解析 Javascript Promise

javascript - ES6 for 循环中 const 的内部原理

reactjs - .map() 不执行任何操作并且没有错误 - react

javascript - 此 Javascript 不适用于 IE,但适用于 Chrome、Firefox 和 Opera

javascript - 如何实现异步生成器以与 Node 可读流进行流传输?

javascript - async-await 只与 promises 一起使用吗?

javascript - 在 JavaScript 中独家使用模板文字?