亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

異步鏈接模式

異步鏈接模式

冉冉說 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 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號