从API获取实时数据到路由
我正在使用以下两个文件从两个API获取数据。 请在下面find我的最低可行的例子:
poloniex.js
const Poloniex = require('poloniex-api-node') const poloniex = new Poloniex() async function getExchangeTicker() { poloniex.returnTicker((err, ticker) => { if (err) { console.log(err.message) } else { //console.log(ticker) return ticker } }) } module.exports = { getExchangeTicker, }
cctx.js
const ccxt = require ('ccxt') async function getExchangeTicker() { const bitfinex = new ccxt.bitfinex({ verbose: true }) const data = await bitfinex.fetchTicker() return data } module.exports = { getExchangeTicker, }
scheduler.js
const exchangePoloniex = require('../exchange/poloniex') const exchangeCCTX = require('../exchange/cctx') async function getAllTickers() { const exchanges = [ exchangePoloniex, exchangeCCTX, ] let res exchanges.forEach((exchange) => { res = exchange.getExchangeTicker() }) return res } async function runScheduler() { let res setInterval(() => { this.res = getAllTickers() }, 3000) console.log("res: " + res) return res } runScheduler()
我正在运行一个调度程序来汇集这些文件中的数据,但只获取res: undefined
back。
任何build议如何正确从这两个API获取数据?
我非常感谢你的答复!
我不知道你正在访问的两个API,所以我不能真正判断你的代码是否来自poloniex.js或cctx.js是好的 – 我假设你可以通过console.logs等告诉你,您需要从每个单独的API数据。
但是我可以在你的scheduler.js文件中看到一些逻辑问题:
- 在
getAllTickers
,您的.forEach
循环会在每次迭代时覆盖res
,因此只有最后一个结果才可见。 - 由于它是一个
async
函数,getAllTickers
返回一个promise。 你将需要使用.then
或类似的东西返回。 - console.log和
runScheduler
返回在setInterval有机会执行之前完成,即使一次,也没有可用的数据。
我想下面的设置可能是你想要的:
const exchangePoloniex = require('../exchange/poloniex') const exchangeCCTX = require('../exchange/cctx') async function getAllTickers() { let updatedTickers = [] updatedTickers[0] = await exchangePoloniex.getExchangeTicker() updatedTickers[1] = await exchangeCCTX.getExchangeTicker() return updatedTickers } function runScheduler() { let tickers setInterval(() => { tickers = getAllTickers() console.log(tickers) // tickers is a promise at this point tickers.then((data) => { console.log(data) // should be the data returned from your apis // store the data in your db }) }, 3000) } runScheduler()
请注意, runScheduler
不一定是asynchronous的,因为你没有做任何事情的返回值 – 所有的工作都在setInterval
callback
如果您需要为响应浏览器请求提供此数据,则可以从数据库中获取数据,并知道它在最近3秒内已更新。