我不清楚你想要发生什么,但你的代码不会捕捉到所有错误。我知道您似乎忽略了所有错误,但以防万一,...
如果你打算使用 async/await 那么你应该全力以赴。这意味着你应该使用fs.promises.readFile
not fs.readFile
。要么,要么您应该fs.readFile
手动或使用util.promisify
.
所以代码变成了
'use strict';
const ccxt = require ('ccxt');
const thing1 = (async () => {
try{
const exchange = new ccxt.one({ enableRateLimit: true })
const tickers = await exchange.fetchTickers()
const obj = { tickers }
const fs = require('fs');
await fs.promises.writeFile("/myproject/file1.txt", JSON.stringify(obj));
} catch {
// catch error here
}
}) ();
const thing2 = (async () => {
try{
const exchange = new ccxt.two({ enableRateLimit: true })
const tickers = await exchange.fetchTickers()
const obj = { tickers }
const fs = require('fs');
await fs.promises.writeFile("/myproject/file2.txt", JSON.stringify(obj));
} catch {
// catch error here
}
}) ();
如果想要同时等待这两件事,那么您可以Promise.all
通过传入一个数组来使用,该数组包含两个异步函数返回的每个 Promise。
'use strict';
const ccxt = require ('ccxt');
const thing1 = (async () => {
try{
const exchange = new ccxt.one({ enableRateLimit: true })
const tickers = await exchange.fetchTickers()
const obj = { tickers }
const fs = require('fs');
await fs.promises.writeFile("/myproject/file1.txt", JSON.stringify(obj));
} catch {
// catch error here
}
}) ();
const thing2 = (async () => {
try{
const exchange = new ccxt.two({ enableRateLimit: true })
const tickers = await exchange.fetchTickers()
const obj = { tickers }
const fs = require('fs');
await fs.promises.writeFile("/myproject/file2.txt", JSON.stringify(obj));
} catch {
// catch error here
}
}) ();
(async() => {
await Promise.all([thing1, thing2]);
// do something after thing1 and thing2
}) ();
当然,除了文件名之外,这两个函数是相同的
'use strict';
const ccxt = require ('ccxt');
async function fetchTickersAndWrite({method, filename}) {
try{
const exchange = new ccxt[method]({ enableRateLimit: true })
const tickers = await exchange.fetchTickers()
const obj = { tickers }
const fs = require('fs');
await fs.promises.writeFile(filename, JSON.stringify(obj));
} catch {
// catch error here
}
}
(async() => {
await Promise.all([
{ method: 'one', filename: `/myproject/file1.txt` },
{ method: 'two', filename: `/myproject/file2.txt` },
].map(fetchTickersAndWrite));
// do something
}) ();