我对 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/