简体   繁体   English

然后Javascript在一个类中承诺

[英]Javascript promise then inside a class

I'm trying to understand how Promises are working and I can't get my piece of code to work. 我试图了解Promise是如何工作的,我无法让我的代码工作。

class Lights {
    constructor(delay) {
        this.blue = 0;
        this.green = 0;
        this.red = 0;
        this.delay = delay;
    }

    fadeIn(color, i) {
        var self = this;
        return new Promise(function(resolve, reject) {
            setTimeout(function () {
                self[color] = i;
                console.log(self[color]);
                i+=5;
                if (i <= 255) {
                    self.fadeIn(color, i);
                }
                resolve(self);
            }, self.delay);
        });
    }

    fadeOut(color, i) {
        var self = this;
        return new Promise(function(resolve, reject) {
            setTimeout(function () {
                self[color] = i;
                console.log(self[color]);
                i-=5;
                if (i >= 0) {
                    self.fadeIn(color, i);
                }
                resolve(self);
            }, self.delay);
        });
    }
}


var lights = new Lights(50);

lights.fadeIn("blue", 0).then(
    lights.fadeOut("blue", 255)
);

Here is a jsFiddle of the code. 这是代码的jsFiddle

The idea behind the code is to set the blue color from 0 to 255 and Then from 255 to 0. How can I do this ? 代码背后的想法是将蓝色设置为0到255 Then从255设置为0.我该怎么做?

You are making recursive calls so on the last call what you resolve is not the resolve in your first promise that you call then on so you could store that first resolve in one property in your class and then call it. 您正在递归调用等最后一次通话是你解决是不是在你的第一个承诺,你叫决心then上,所以你能说先解决存储在您的类中的一个属性,然后调用它。

 class Lights { constructor(delay) { this.blue = 0; this.green = 0; this.red = 0; this.delay = delay; this.fadeInResolve = null; this.fadeOutResolve = null; } fadeIn(color, i) { return new Promise((resolve, reject) => { if (!this.fadeInResolve) { this.fadeInResolve = resolve } setTimeout(() => { this[color] = i; console.log(this[color]); i += 5; if (i <= 255) this.fadeIn(color, i); else this.fadeInResolve(this) }, this.delay); }); } fadeOut(color, i) { return new Promise((resolve, reject) => { if (!this.fadeOutResolve) { this.fadeOutResolve = resolve } setTimeout(() => { this[color] = i; console.log(this[color]); i -= 5; if (i >= 0) this.fadeOut(color, i); else this.fadeOutResolve(this) }, this.delay); }); } } var lights = new Lights(50); lights.fadeIn("blue", 0).then(() => { console.log('Fade in done') lights.fadeOut("blue", 255).then(() => { console.log('Fade out done') }) }); 

Promise.prototype.then() should take a callback function and the recursion is not waiting. Promise.prototype.then()应该采用回调函数,递归不等待。 Consider this code which can be used to do the same thing: 考虑一下这段代码可以用来做同样的事情:

 //promisify :) function timer(delay) { return new Promise(function (resolve, reject) { setTimeout(function () { resolve(); }, delay); }); } class _Modulator { constructor(_resolution = 255, _delay = 5) { /* assert resolution and delay > 0; */ this._resolution = _resolution; this._delay = _delay; this._counter = 0; this._running = false; } start() { console.log("timer start"); this._running = true; this._start(); } _start() { return timer(this._delay).then(() => { if (this._running === true) { this._counter += 1; console.log("tick"); this._onTick(); /* care should be taken to ensure this will always catch, eg, * correcting init */ if (this._counter === this._resolution) { this._counter = 0; this._onCycle(); } this._start(); } }); } stop() { this._running = false; console.log("timer stopped"); } _onTick() { console.log("tick handle: %s", this._counter); } _onCycle() { console.log("new cycle"); } } class UpDownModulator extends _Modulator { constructor(_resolution = 255, _delay = 5) { super(_resolution, _delay); this._dir = 1; } _onTick() { console.log("tick handle: %s", this.getCounter()); } _onCycle() { this._toggleDirection(); console.log("new cycle: going %s", this.getDirection()); } _toggleDirection() { this._dir ^= 1; } getCounter() { return this._dir ? this._counter : this._resolution - this._counter; } getDirection() { return this._dir ? "up" : "down"; } } let c = new UpDownModulator(); c.start(); 

You can create a ColorFader class that depends on a Modulator and observe it. 您可以创建一个依赖于调制器并观察它的ColorFader类。 This creates clean abstractions that adhere to SRP. 这创建了符合SRP的干净抽象。

I hope this helps! 我希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM