javascript - promise 所有并获得请求

标签 javascript node.js express promise

所以我很难理解完成任务需要采取的步骤。我想获得所有用户的加密硬币“监视列表”(我已经完成了)。然后根据保存在他们的监视列表中的内容从 coinmarketcap api 返回更新的数据。有人告诉我可以使用 Promise.all() 高效地完成此任务。我本质上是从 mongodb 监视列表中查找/映射硬币(“比特币”)的 ID,然后使用映射的 ID 作为硬币参数运行 get coins 函数吗?谁能就此提供一些指导?

我试过这样做,但没有成功。也就是说 undefined 不是一个函数。

CryptoWatchlist.find()
.then(watchlists => watchlists.map(watchlist => watchlist.id))
.then(id => Promise.all(getCoins(id)))

/router/watchlist.js

router.get('/watchlist', (req, res) => {
  CryptoWatchlist.find()
    .then(watchlists =>
      res.json(watchlists.map(watchlist => watchlist.serialize()))
    )
    .catch(err => {
      console.error(err);
      res.status(500).json({ message: 'Internal server error' });
    });
});

/api.js

const fetch = require('node-fetch');

function getCoins(coin) {
  return fetch(`https://api.coinmarketcap.com/v1/ticker/${coin}`).then(
    response => {
      return response.json();
    }
  );
}

module.exports = getCoins;

最佳答案

你离得不远了。这应该让你走上正确的轨道:

const watchlistPromises = CryptoWatchlist.find()
.then(watchlists => watchlists.map(({ id }) => getCoins(id));

Promise.all(watchlistPromises).then(responses => {
    // Process responses
});

responses 将是一组 getCoin promise 响应,其顺序与监视列表数组相同。

这个想法是将列表中的每个硬币映射到 coinmarketcap API 的请求。如果您的列表很大,您将很难使用他们的 API。您可能想看看他们的 API 是否有在一个请求中发送多个符号的选项。

关于javascript - promise 所有并获得请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49090004/

相关文章:

javascript - 如何在 Sequelize 中获取模型的所有用户名

javascript - 如何对字体系列使用 ng-class

javascript - Visual Studio 2019 中用于 Node js 应用程序的 Mocha 在引用或需要另一个文件时未在测试资源管理器中显示测试

javascript - 未捕获错误 : Expected `onClick` listener to be a function, 取而代之的是得到了 `object` 类型的值

javascript - Neo4j session .catch 错误 : structure (127, [[对象对象]])

node.js - 跨域应用程序的快速 session 不发送 cookie

javascript - INSTAGRAM:授予公共(public)内容范围的权限,但访问 token 仍然给出未授权的错误

javascript - 如何从数组中删除具有相同值的项目

node.js - 在 Express 中使用参数在 url 上提供静态文件

node.js - 在 Nodejs Express 中的 ejs 模板内渲染图像