【发布时间】:2016-08-18 02:09:17
【问题描述】:
我正在构建一个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);
}
【问题讨论】:
-
firstRequest ... 函数中有什么?这些是真正的异步功能吗?也许那里有一些内部序列化。
-
它们是返回承诺的异步函数。
-
实际上它们都都并行运行,问题是
res.json没有等待它们。 You cannot useforEach.
标签: node.js express promise ecmascript-6 generator