承诺所有并获得请求

问题描述 投票:3回答:3

所以我很难理解为完成任务需要采取的步骤。我希望所有用户都能获得加密硬币的“关注列表”(我已经完成了)。然后根据他们的监视列表中保存的内容,从coinmarketcap api返回更新的数据。有人告诉我,我可以使用Promise.all()有效地完成这项工作。我是否主要从mongodb监视列表中找到/映射硬币的id('bitcoin')然后运行get coins函数并将映射的id作为硬币参数?任何人都可以提供一些指导吗?

我试图做这样的事情,但那不起作用。这表示undefined不是一个功能。

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

/router/watchlist.就是

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.就是

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;
javascript node.js express promise
3个回答
0
投票

你离我不太远。这应该让你走上正轨:

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

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

responses将是一系列getCoin承诺响应,其顺序与watchlist数组相同。

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


0
投票

在得到的承诺数组上使用Promise.all:

const promises = CryptoWatchlist.find()
  .then(watchlists => watchlists.map(watchlist => watchlist.id))
  .then(id => getCoins(id))

Promise.all(promises)
  .then(data => {
    console.log(data)
  })

0
投票

替代其他答案,但更像是原始代码的FP风格

CryptoWatchlist.find()
.then(watchlists => 
    Promise.all(watchlists.map(({id}) => 
        getCoins(id)
    ))
)
© www.soinside.com 2019 - 2024. All rights reserved.