我正在构建一个express.js
Web应用程序,对于其中一个API请求,我需要并行多个用户帐户的多个请求并返回一个对象。
我尝试使用generators
和Promise.all
,但我有两个问题:
这是我写的代码:
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);
}
答案 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
}
这应该是整个代码。
协同程序很棒,但它们对于同步异步内容很有用 - 在你的情况下,你确实需要并发功能。