【发布时间】:2019-07-15 22:23:55
【问题描述】:
使用 Node.js,我的任务是改进我创建的代码。此代码执行 60 个 HTTP 请求并为此使用库。
处理所有 HTTP 请求并将每个请求保存到文件需要 30 秒!
据说可以在 3 秒内完成这些请求:
1.正确管理异步承诺
2。更智能的缓存
3.不使用集群
4.只添加一次开销
恐怕我不知道从哪里开始了解我到底能做什么。
所以下面的代码得到了一个包含 60 项的数组,其中每一项都是一个 HTTP 请求:
const exchanges = ccxt.exchanges
这些进入:worker = async 函数并在代码末尾:await Promise.all(workers) 等待它们完成。
我不知道从哪里开始才能真正降到 3 秒。怎样才能提高这段代码的速度?
'use strict';
const ccxt = require ('ccxt')
, log = require ('ololog').noLocate // npm install ololog
, fs = require ('fs')
// the numWorkers constant defines the number of concurrent workers
// those aren't really threads in terms of the async environment
// set this to the number of cores in your CPU * 2
// or play with this number to find a setting that works best for you
, numWorkers = 8
;(async () => {
// make an array of all exchanges
const exchanges = ccxt.exchanges
.filter (id => ![ 'cap1', 'cap2' ].includes (id))
// instantiate each exchange and save it to the exchanges list
.map (id => new ccxt[id] ({
'enableRateLimit': true,
}))
// the worker function for each "async thread"
const worker = async function () {
// while the array of all exchanges is not empty
while (exchanges.length > 0) {
// pop one exchange from the array
const exchange = exchanges.pop()
// check if it has the necessary method implemented
if (exchange.has['fetchTickers']) {
// try to do "the work" and handle errors if any
try {
// fetch the response for all tickers from the exchange
const tickers = await exchange.fetchTickers()
// make a filename from exchange id
const filename = '/myproject/tickers/' + exchange.id + 'Tickers.json'
// save the response to a file
fs.writeFileSync(filename, JSON.stringify({ tickers }));
} catch (e) { } //Error
}
}
}
// create numWorkers "threads" (they aren't really threads)
const workers = [ ... Array (numWorkers) ].map (_ => worker ())
// wait for all of them to execute or fail
await Promise.all (workers)
}) ()
【问题讨论】:
-
谁说有可能?我的意思是,如果您要以同步方式执行此操作,而不是在执行下一个呼叫之前等待每个呼叫完成。似乎您不想同步进行。
-
减少您正在执行的请求数量。例如,找到一种方法将“exchanges”中的所有“fetchTickers”组合到一个请求中。
-
顺便说一句,如果性能很重要,您为什么要使用
writeFileSync?当同步操作运行时,节点事件循环被阻塞。 -
@James 我相信库中不可能将所有“fetchTickers”合并到一个请求中,因为它是完全不同的 URL
-
@Alberti Buonarroti 是的,这是我可以改进的一件事。我想知道是否有可能以某种比现在编码的更“并行”的方法运行这些请求?我得到的提示是以更明智的方式使用 async/await/promises。
标签: javascript node.js http promise async-await