为了账号安全,请及时绑定邮箱和手机立即绑定

异步链接模式

异步链接模式

冉冉说 2021-11-18 09:49:03
考虑以下情况:var Calc = function () {   // proprties   this.value = 0   // handler's   this.Add = (__value) => { this.value = this.value + __value; return this }   this.Subtract = (__value) => { this.value = this.value - __value; return this }}var = (new Calc()).Add(2).Subtract(1) // console.log() => 1但是如果你在 async 中包装 Object 等待类似的东西var Calc = async function () {   // proprties   this.value = 0   // handler's   this.Add = async (__value) => { this.value = this.value + __value; return this }   this.Subtract = async (__value) => { this.value = this.value - __value; return this }}(await new Calc()).Add(2).Subtract(1) // console.log() => undefined(await (await new Calc()).Add(2)).Subtract(1) // console.log() => 1我知道返回 Promise 的原因需要解决,因为您只需将代码包装在 () 中,一旦执行语句,您就可以继续链。我在寻找什么。await newCalc().Add(2).Subtract(1) // console.log() => 1
查看完整描述

1 回答

?
扬帆大鱼

TA贡献1799条经验 获得超9个赞

警告await只能在async函数内部使用,您想要的那种 API 是可能的,只是稍微复杂一些。


大量的库,例如knex,jQuery和nightmare.js实现链接以组成异步操作。但是可链接的方法不是异步的。相反,异步操作仅在操作结束时(当您想要结果时)执行,但方法本身是同步的。在的情况下knex,例如,异步操作仅执行时.then()被调用。


这是您可以做到的一种方法:


function Calc () {

    this.operations = [];

    this.value = 0;

}


Calc.prototype = {

    add: function (x) {

        // schedule a function that performs async addition:

        this.operations.push(() => {

            return new Promise(ok => {

                ok(this.value + x);

            });

        });

        return this;

    },

    subtract: function (x) {

        // schedule a function that performs async subtraction:

        this.operations.push(() => {

            return new Promise(ok => {

                ok(this.value - x);

            });

        });

        return this;

    },

    // THIS IS WHERE WE DO OUR MAGIC

    then: async function (callback) {

        // This is finally where we can execute all our

        // scheduled async operations:

        this.value = 0;

        for (let i=0; i<this.operations.length; i++) {

            this.value = await operations[i]();

        }

        return callback(this.value); // since the await keyword will call our

                                     // then method it is the responsibility of

                                     // this method to return the value.

    }

}

现在你可以像这样使用它:


async function main () {

    let x = await new Calc().add(2).subtract(1);

    console.log(x);

}

main();

请注意,上面的代码在功能上等效于:


new Calc().add(2).subtract(1).then(x => console.log(x));


查看完整回答
反对 回复 2021-11-18
  • 1 回答
  • 0 关注
  • 123 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信