[英]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.