gpt4 book ai didi

javascript - 装饰 Javascript Promise.then 以便参数函数接收附加参数

转载 作者:行者123 更新时间:2023-11-30 11:50:02 24 4
gpt4 key购买 nike

我有以下使用 ES6 Promise 的代码:

const ctx = {}
Promise.resolve()
.then(() => doSomethingWith(ctx))
.then((retValue) => doSomethingElseWith(retValue, ctx))

我希望能够做这样的事情:

const ctx = {}
using(ctx)
.then((ctx) => doSomethingWith(ctx))
.then((retValue, ctx) => doSomethingElseWith(retValue, ctx))

对于第一个 then,我有这样的东西:

function using(ctx) {
const p = Promise.resolve()
p.then = (fn) => withCtx(fn, ctx)
return p
}

function withCtx (fn, ctx) {
const p = new Promise((resolve) => {
resolve(fn.apply(this, [ctx]))
})
return p
}

但我希望它能够处理第二个情况,它同时采用先前的 promise 返回值和上下文......我怎么能有这部分:

fn.apply(this, [ctx]) // want previous promise returned value and ctx here !

处理 fn 已经采用我们想要传播的参数的情况...上面描述的 retValue 情况。

有什么想法吗? (我想在后面介绍的用例是能够随时停止 Promise 链,将值保存在磁盘上并随时重新启动,并从磁盘恢复更改的上下文)

最佳答案

老实说,我认为这很令人困惑,而且可能是一种反模式,但是你能简单地通过添加一个额外的 then 来在 promise 之间传递可变状态吗

Promise.resolve({}) 
.then(ctx => doSomethingWith(ctx)
.then(ret => ({ret, ctx})))
.then(({ret, ctx}) => doSomethingElseWith(ret, ctx))

第二个 then 在第一个里面,因此在输入状态上有一个闭包,它可以在将变异的上下文传递到下一阶段之前用转换后的值装饰它。这是在不泄漏对全局上下文的任何引用的情况下实现的。

显示扩展模式后的样子...

function trans (that, y) {
console.dir(y);
return new Promise(res =>
setTimeout(res.bind(null, that.op(y)), 1000)
)
}

Promise.resolve({ret: 0, ctx: {op: _ => _ + 2}})
.then(({ret, ctx}) => trans(ctx, ret)
.then(ret =>({ ret, ctx}))
)
.then(({ret, ctx}) => trans(ctx, ret)
.then(ret =>({ ret, ctx}))
)
.then(({ret, ctx}) => trans(ctx, ret)
.then(ret =>({ ret, ctx}))
)
.then(({ret, ctx}) => trans(ctx, ret)
.then(ret =>({ ret, ctx}))
)
.then(ctx => console.dir(ctx));
.catch(console.log.bind(console));

关于javascript - 装饰 Javascript Promise.then 以便参数函数接收附加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39747333/

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