异步链接模式

问题描述 投票:0回答:1

考虑以下情况:

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

但是如果您以异步方式包装对象,则等待类似的东西

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

考虑以下情况:var Calc = function(){//属性this.value = 0 //处理程序的this.Add =(__value)=> {this.value = this.value + __value;返回this} this.Subtract = ...

javascript node.js
1个回答
2
投票

[请注意,await仅可在async函数内使用,可以使用所需的API,只是稍微复杂一点。

© www.soinside.com 2019 - 2024. All rights reserved.