ES6 – 并行地为多个用户帐户提出多个请求

我正在构build一个express.js Web应用程序,并且我需要为多个用户帐户并行请求多个请求,并返回一个对象。
我尝试使用generatorsPromise.all但我有2个问题:

  1. 我不会并行运行所有用户帐户。
  2. 我的代码在响应已经返回后结束。

这是我写的代码:

 function getAccountsDetails(req, res) { let accounts = [ '1234567890', '7856239487']; let response = { accounts: [] }; _.forEach(accounts, Promise.coroutine(function *(accountId) { let [ firstResponse, secondResponse, thirdResponse ] = yield Promise.all([ firstRequest(accountId), secondRequest(accountId), thirdRequest(accountId) ]); let userObject = Object.assign( {}, firstResponse, secondResponse, thirdResponse ); response.accounts.push(userObject); })); res.json(response); } 

_.forEach不知道Promise.coroutine,它不使用返回值。

既然你已经使用蓝鸟,你可以使用它的承诺意识帮手:

 function getAccountsDetails(req, res) { let accounts = [ '1234567890', '7856239487']; let response = { accounts: [] }; return Promise.map(accounts, (account) => Promise.props({ // wait for object firstResponse: firstRequest(accountId), secondResponse: secondRequest(accountId), thirdResponse: thirdRespones(accountId) })).tap(r => res.json(r); // it's useful to still return the promise } 

这应该是整个代码。

协程很好,但是对于同步asynchronous的东西很有用 – 在你的情况下,你确实需要并发function。