首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Ramda管道中使用Promise.all

在Ramda管道中使用Promise.all
EN

Stack Overflow用户
提问于 2020-02-28 06:04:20
回答 2查看 799关注 0票数 5

Promise.all是如何在ramda管道中使用的?我想我漏掉了一些愚蠢的东西。

代码语言:javascript
复制
const pipeline: Function = R.pipe(
    R.map((record) => record.body),
    R.map(JSON.parse),
    R.map(asyncFunction),
    console.log
);

返回承诺数组(Promise.all的输入)

代码语言:javascript
复制
[ Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> } ]

但是,如果我试图等待Promise.all解决这些承诺,如下所示:

代码语言:javascript
复制
const pipeline: Function = R.pipe(
    R.map((record) => record.body),
    R.map(JSON.parse),
    R.map(asyncFunction),
    Promise.all,
    R.andThen(useTheReturn)
);

最后出现一个类型错误,说明我试图使用Promise.all作为构造函数类型。

代码语言:javascript
复制
{
    "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)"
    ]
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-02-28 06:41:20

您需要将Promise.all绑定到Promise

代码语言:javascript
复制
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)
);

演示:

代码语言:javascript
复制
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)
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>

票数 5
EN

Stack Overflow用户

发布于 2020-05-20 08:34:16

我编写了一个名为红宝石的库,它简化了这一点,因为您不需要担心绑定承诺,也不需要自己使用Promise.all。

代码语言:javascript
复制
import { pipe, map } from 'rubico'

const pipeline: Function = pipe([
  map((record) => record.body),
  map(JSON.parse),
  map(asyncFunction),
  console.log,
]);

pipe类似于ramda的管道,因为它将函数链在一起,但是在异步函数的情况下,它将在将值传递给下一个函数之前解析返回的承诺。

map就像ramda的映射,但它只适用于异步函数。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60446102

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档