ES6 - 并行多个用户帐户的多个请求

时间:2016-08-17 16:52:19

标签: node.js express promise ecmascript-6 generator

我正在构建一个express.js Web应用程序,对于其中一个API请求,我需要并行多个用户帐户的多个请求并返回一个对象。
我尝试使用generatorsPromise.all,但我有两个问题:

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

    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);
    }
    

1 个答案:

答案 0 :(得分:1)

_.forEach不知道Promise.coroutine,也没有使用返回值。

由于您已经在使用bluebird,因此您可以使用其承诺感知帮助程序:

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
}

这应该是整个代码。

协同程序很棒,但它们对于同步异步内容很有用 - 在你的情况下,你确实需要并发功能。