gpt4 book ai didi

node.js - ES6 - 并行向多个用户帐户发出多个请求

转载 作者:太空宇宙 更新时间:2023-11-04 00:36:01 25 4
gpt4 key购买 nike

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

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

最佳答案

_.forEach 不知道 Promise.coroutine,并且它不使用返回值。

由于您已经在使用 bluebird,因此您可以使用它的 Promise 感知助手:

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
}

这应该是完整的代码。

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

关于node.js - ES6 - 并行向多个用户帐户发出多个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39002298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com