javascript - 如何减少多个 Promise.all? [英] javascript - How do I reduce multiple Promise.all?

查看:43
本文介绍了javascript - 如何减少多个 Promise.all?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 reduce 中使用 Promise.all 并且无法让我的 function 工作,除非只有一个我的阵列中的用户.reduce 的起始对象是一个 Promise.第一次通过 reducePromise.all 可用.第二次通过,.all 不可用.

I am trying to use a Promise.all inside of a reduce and cannot get my function to work, unless there is only one user in my array. The starting object of the reduce is a Promise. The first time through the reduce, the Promise has .all available on it. The second time through, the .all is not available.

return UserQueries.addUsersOnCasefileCreate(input).then(users => {
  return users.reduce((promise, user) => {
    return promise.all([
      AddressQueries.addAddress(user.address, user.userId, input.orgId),
      EmailQueries.addEmail(user.emails, user.userId, input.orgId),
      PhoneQueries.addPhones(user.phones, user.userId, input.orgId)
    ])
    .then(() => Promise.resolve(user))
  }, Promise);
})

我该如何执行此操作?

推荐答案

你用 Promise 初始化,这是一个函数,虽然返回一个已解析的 Promise 对象,其中两个不一样.

You initialize with Promise which is a function, though return a resolved Promise object, where the two are not the same.

你可以用Promise.resolve()初始化,调用promise.then(),然后用<返回Promise.all()code>.then() 链接在第一个 .then() 中,它将 Promise 对象传递到 .reduce() 处的下一次迭代>.

You can initialize with Promise.resolve(), call promise.then(), then return Promise.all() with .then() chained within first .then(), which passes Promise object to next iteration at .reduce().

return UserQueries.addUsersOnCasefileCreate(input).then(users => {
  return users.reduce((promise, user) => {
    return promise.then(() => Promise.all([
      AddressQueries.addAddress(user.address, user.userId, input.orgId),
      EmailQueries.addEmail(user.emails, user.userId, input.orgId),
      PhoneQueries.addPhones(user.phones, user.userId, input.orgId)
    ]))
    .then(() => user))
  }, Promise.resolve());
})

这篇关于javascript - 如何减少多个 Promise.all?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆