简体   繁体   English

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

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

I want to transform an imperative Promise to a functional Task in a principled fashion:我想以有原则的方式将命令式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"

The resolution case works but the rejection doesn't, because Promise s are eagerly triggered.解决案例有效,但拒绝无效,因为急切地触发了Promise If I dropped the catch handler I would have to put the entire computation into a try / catch statement.如果我放弃了catch处理程序,我将不得不将整个计算放入try / catch语句中。 Is there a more viable alternative?有没有更可行的选择?

You don't need .catch(x => x) , which turns your rejected promise into an resolved one.您不需要.catch(x => x) ,这会将您拒绝的 promise 变成已解决的。 You shouldn't get an "uncaught error" since you have a catch inside your taskFromPromise function.您不应收到“未捕获的错误”,因为您的taskFromPromise function 中有一个catch Removing the .catch(x => x) does work and lands you in .catch(x => rej(`Error: ${x}`)) instead.删除.catch(x => x)确实有效,并将您置于.catch(x => rej(`Error: ${x}`))中。

However removing .catch(x => x) does throw "TypeError: rej is not a function".但是删除.catch(x => x)确实会抛出“TypeError:rej 不是函数”。 From your code sample it it seems like your .task(...) (in tx.task(...) and ty.task(...) ) expects two functions.从您的代码示例看来,您的.task(...) (在tx.task(...)ty.task(...) )需要两个函数。 The first one is called if the promise resolves, the second one if the promise is rejected.如果 promise 解决,则调用第一个,如果 promise 被拒绝,则调用第二个。 Providing both functions leaves me with a working code snippet.提供这两个函数给我留下了一个有效的代码片段。

 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