如何使用Promises实现流畅的界面?

我想使此代码正常工作

data.append(data2[['Away','Home']],ignore_index=True,sort=False)\
    .replace(np.nan,'')

我创建了一个带有数据数组的类来保存项目。和steps数组来保存操作。然后我使用了可链接的诺言来执行它们。那是做我想要达到的最好的方法吗?我真的需要将操作存储在数组中吗?

$('start') // push initial value to an array
.addItem(2) // add another value
.printAll() // print everything in array
.delay(2000) // wait x seconds
.addItem(5)
.printAll()
.start(); // execute all the commands before this line
woaizhaokai2009 回答:如何使用Promises实现流畅的界面?

尽管根据我的说法,您的问题属于https://codereview.stackexchange.com/,但我尝试着考虑另一种没有承诺的实现。它仅适用于闭包和回调:

class Sync {

    constructor() {}

    init(startValue) {
        this.data = [startValue];
        this.steps = [];
        return this;
    }

    addItem(value) {
        const append = v => this.data.push(v);
        this._addStep(append,value);
        return this;
    }

    printAll() {
        this._addStep(v => console.log(v.join()),this.data);
        return this;
    }

    delay(value) {
        this._addStep(window.setTimeout,value);
        return this;
    }

    _addStep(fun,...args) {
        this.steps.push({
            fun,args
        });
    }

    start() {
        let finalFunction;
        this.steps.reverse().forEach(({ fun,args }) => {
            if (fun === window.setTimeout) {
                finalFunction = finalFunction ? encloseFunctionWithArgs(null,null,finalFunction,next => setTimeout(next,...args)) : null;
            } else {
                finalFunction = encloseFunctionWithArgs(fun,args,finalFunction);
            }

        });
        finalFunction();
        return this;
    }
}

function encloseFunctionWithArgs(fun,next,trigger) {
    return function () {
        if (fun)
            fun(args);
        if (next)
            trigger ? trigger(next) : next();
    }
}

const lib = new Sync();
const $ = lib.init.bind(lib);
$('start')
.addItem(2)
.printAll()
.delay(2000)
.addItem(5)
.printAll()
.start();

编辑

我终于设法实现了您想要的:

class Sync {

    constructor() {}

    init(startValue) {
        this.promise = new Promise(resolve => this.start = resolve).then(() => [startValue]);
        return this;
    }

    addItem(value) {
        this.promise = this.promise.then(v => {
                v.push(value);
                return v;
            });
        return this;
    }

    printAll() {
        this.promise = this.promise.then(v => {
                console.log(v.join());
                return v;
            });
        return this;
    }

    delay(value) {
        this.promise = this.promise.then(v => new Promise(resolve => setTimeout(() => resolve(v),value)));
        return this;
    }
}

const lib = new Sync();
const $ = lib.init.bind(lib);
$('start')
.addItem(2)
.printAll()
.delay(2000)
.addItem(5)
.printAll()
.start();

本文链接:https://www.f2er.com/2822547.html

大家都在问