gpt4 book ai didi

javascript - 异步链接模式

转载 作者:行者123 更新时间:2023-12-01 00:33:06 24 4
gpt4 key购买 nike

考虑以下情况:

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

但是如果你将 Object 包装在 async wait 中,比如

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

最佳答案

需要注意的是,await 只能在 async 函数中使用,您想要的 API 类型是可能的,只是稍微复杂一点。

很多库,例如knexjQuerynightmare.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));

关于javascript - 异步链接模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58347610/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com