所以我很难理解完成任务需要采取的步骤。我想获得所有用户的加密硬币“监视列表”(我已经完成了)。然后根据保存在他们的监视列表中的内容从 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/