我正在構建一個express.js
web應用程序,並且我需要爲其中一個API請求並行發出多個用戶帳戶請求並返回一個對象。
我嘗試使用generators
和Promise.all
,但我有2個問題:
ES6 - 爲多個用戶帳戶並行發出多個請求
- 我不爲所有用戶帳戶並行運行。
- 我的代碼在響應已經返回後結束。
這裏是我寫的代碼:
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);
}
第一次請求...函數中有什麼?那些真正的異步功能?也許這裏有一些內部序列化。 –
它們是返回承諾的異步函數。 –
其實他們都*並行運行,問題在於'res.json'沒有在等待。 [你不能使用'forEach'](http://stackoverflow.com/q/37576685/1048572)。 – Bergi