【问题标题】:Promise All and Get Requests承诺所有并获取请求
【发布时间】:2018-08-11 21:37:08
【问题描述】:

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

我试图做这样的事情,但没有奏效。也就是说 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;

【问题讨论】:

  • 您看到的确切错误是什么?
  • @randominstanceOfLivingThing 我目前看到的确切错误是 (node:17012) UnhandledPromiseRejectionWarning: Unhandled PromiseRejectionWarning: Unhandled Promise Rejection (rejection id: 2): TypeError: undefined is not a function (node:17012) [DEP0018] DeprecationWarning :不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。

标签: javascript node.js express promise


【解决方案1】:

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

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

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

responses 将是一个 getCoin 承诺响应数组,与观察列表数组的顺序相同。

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

【讨论】:

  • 我确实检查了他们的 API 是否可以在一个请求中获取多个符号,但他们不能。我相信这就是我被告知使用 Promise.all 的原因。另外,我试过这个,我收到以下错误:TypeError: undefined is not a function at Function.all ()
  • @jpatel701 你用的是什么版本的节点?
  • watchlists 一个实际的数组 - 一些数据库的结果是“类似数组”但实际上不是数组......并且没有 .map 方法
  • @AndyGaskell 我正在使用 v8.9.2
  • 是的,从你所看到的......你能确认.map方法存在吗?即console.log(typeof watchlists.map)的输出是什么
【解决方案2】:

在结果数组上使用 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)
  })

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-17
      • 1970-01-01
      • 1970-01-01
      • 2018-11-09
      • 1970-01-01
      • 2018-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多