繁体   English   中英

如何将命令式 Promise 转换为功能性任务?

[英]How to transform an imperative Promise to a functional Task?

我想以有原则的方式将命令式Promise转换为功能性Task

 const record = (type, o) => (o[type.name || type] = type.name || type, o); const thisify = f => f({}); const taskFromPromise = p => Task((res, rej) => p.then(res).catch(x => rej(`Error: ${x}`))); const Task = task => record( Task, thisify(o => { o.task = (res, rej) => task(x => { o.task = k => k(x); return res(x); }, rej); return o; })); const tx = taskFromPromise(Promise.resolve(123)), ty = taskFromPromise(Promise.reject("reason").catch(x => x)); // ^^^^^ necessary to avoid uncaught error tx.task(console.log); // 123 ty.task(console.log); // "reason" but should be "Error: reason"

解决案例有效,但拒绝无效,因为急切地触发了Promise 如果我放弃了catch处理程序,我将不得不将整个计算放入try / catch语句中。 有没有更可行的选择?

您不需要.catch(x => x) ,这会将您拒绝的 promise 变成已解决的。 您不应收到“未捕获的错误”,因为您的taskFromPromise function 中有一个catch 删除.catch(x => x)确实有效,并将您置于.catch(x => rej(`Error: ${x}`))中。

但是删除.catch(x => x)确实会抛出“TypeError:rej 不是函数”。 从您的代码示例看来,您的.task(...) (在tx.task(...)ty.task(...) )需要两个函数。 如果 promise 解决,则调用第一个,如果 promise 被拒绝,则调用第二个。 提供这两个函数给我留下了一个有效的代码片段。

 const record = (type, o) => (o[type.name || type] = type.name || type, o); const thisify = f => f({}); const taskFromPromise = p => Task((res, rej) => p.then(res).catch(x => rej(`Error: ${x}`))); const Task = task => record( Task, thisify(o => { o.task = (res, rej) => // expects two functions task(x => { o.task = k => k(x); return res(x); }, rej); return o; })); const tx = taskFromPromise(Promise.resolve(123)), ty = taskFromPromise(Promise.reject("reason")); // removed.catch(x => x) tx.task(console.log, console.log); // provide two functions ty.task(console.log, console.log); // ^ ^ // if resolved if rejected

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM