Your nested callback isn't async
(note: the following snippet just illustrates a solution to this specific problem, but full solution will be below):
let parse = (num) =>{
let files = ['p.txt', 'q.txt', 'r.txt', 's.txt', 't.txt', 'u.txt', 'v.txt', 'w.txt', 'x.txt', 'z.txt'];
fs.readFile('./data txt/' + files[num], 'utf8', async (err, data) => {
if(err){
console.log(err)
}
await test(obj, 'data', data)
});
};
That's why you get the SyntaxError
.
In order to make the entire function async
, you'll have to get rid of the callback-style fs.readFile()
. You can use fs.promises
(available since Node 10 I think):
let parse = async (num) =>{
let files = ['p.txt', 'q.txt', 'r.txt', 's.txt', 't.txt', 'u.txt', 'v.txt', 'w.txt', 'x.txt', 'z.txt'];
try {
const data = await fs.promises.readFile('./data txt/' + files[num], 'utf8')
return await test(obj, 'data', data)
} catch (err) {
console.log(err);
}
};
Or if you can't use this new API, you can use util.promisify()
:
const readFileAsync = require('util').promisify(fs.readFile);
let parse = async (num) =>{
let files = ['p.txt', 'q.txt', 'r.txt', 's.txt', 't.txt', 'u.txt', 'v.txt', 'w.txt', 'x.txt', 'z.txt'];
try {
const data = await readFileAsync('./data txt/' + files[num], 'utf8')
return await test(obj, 'data', data)
} catch (err) {
console.log(err);
}
};
Or, if you feel savvy (don't!), you can promisify the function yourself and using raw Promise
:
let parse = (num) => new Promise((resolve, reject) => {
let files = ['p.txt', 'q.txt', 'r.txt', 's.txt', 't.txt', 'u.txt', 'v.txt', 'w.txt', 'x.txt', 'z.txt'];
fs.readFile('./data txt/' + files[num], 'utf8', (err, data) => {
if(err){
console.log(err)
}
resolve(test(obj, 'data', data));
});
});