[英]Using Promise.all inside a Ramda pipe
Promise.all
如何在 ramda 管道中使用? 我想我在這里錯過了一些愚蠢的東西。
const pipeline: Function = R.pipe(
R.map((record) => record.body),
R.map(JSON.parse),
R.map(asyncFunction),
console.log
);
返回一個承諾數組( Promise.all
的輸入)
[ Promise { <pending> },
Promise { <pending> },
Promise { <pending> },
Promise { <pending> },
Promise { <pending> },
Promise { <pending> },
Promise { <pending> },
Promise { <pending> },
Promise { <pending> },
Promise { <pending> } ]
但是,如果我嘗試使用Promise.all
等待這些承諾解決,如下所示:
const pipeline: Function = R.pipe(
R.map((record) => record.body),
R.map(JSON.parse),
R.map(asyncFunction),
Promise.all,
R.andThen(useTheReturn)
);
我最終得到一個類型錯誤,指出我正在嘗試使用Promise.all
作為構造函數類型。
{
"errorType": "TypeError",
"errorMessage": "#<Object> is not a constructor",
"stack": [
"TypeError: #<Object> is not a constructor",
" at all (<anonymous>)",
" at /var/task/node_modules/ramda/src/internal/_pipe.js:3:14",
" at /var/task/node_modules/ramda/src/internal/_arity.js:11:19",
" at Runtime.exports.handler (/var/task/lambda/data-pipeline/1-call-summary-ingestion/index.js:14:19)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
]
}
您需要將Promise.all
綁定到Promise
:
const pipeline: Function = R.pipe(
R.map((record) => record.body),
R.map(JSON.parse),
R.map(asyncFunction),
R.bind(Promise.all, Promise),
R.andThen(useTheReturn)
);
演示:
const pipeline = R.pipe( R.bind(Promise.all, Promise), R.andThen(R.sum) ); const promise1 = Promise.resolve(10) const promise2 = 20 const promise3 = new Promise((resolve) => setTimeout(resolve, 100, 30)) const result = pipeline([promise1, promise2, promise3]) result.then(console.log)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>
我編寫了一個名為rubico的庫,它使這變得更簡單,因為您無需擔心綁定 Promise 或自己使用 Promise.all。
import { pipe, map } from 'rubico'
const pipeline: Function = pipe([
map((record) => record.body),
map(JSON.parse),
map(asyncFunction),
console.log,
]);
pipe
類似於 ramda 的管道,因為它將函數鏈接在一起,但在異步函數的情況下,它將在將值傳遞給下一個函數之前解析返回的承諾。
map
就像 ramda 的 map,但它只適用於異步函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.