2016-08-17 53 views
1

我正在構建一個express.js web應用程序,並且我需要爲其中一個API請求並行發出多個用戶帳戶請求並返回一個對象。
我嘗試使用generatorsPromise.all,但我有2個問題:
ES6 - 爲多個用戶帳戶並行發出多個請求

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

第一次請求...函數中有什麼?那些真正的異步功能?也許這裏有一些內部序列化。 –

+0

它們是返回承諾的異步函數。 –

+0

其實他們都*並行運行,問題在於'res.json'沒有在等待。 [你不能使用'forEach'](http://stackoverflow.com/q/37576685/1048572)。 – Bergi

回答

1

_.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 
} 

這應該是全部的代碼。

協程很棒,但它們對於同步異步內容非常有用 - 在您的情況下您確實需要併發功能。

+0

'r'是一個對象數組嗎? –

+1

我不認爲你應該在循環中的每個承諾上調用'res.json'。而是'Promise.map/all(...).then(r => res.json(r),e => res.err(e))' – Bergi

+0

哎呦,我錯放了我的'''謝謝! –