简体   繁体   中英

how could I use async/await for that function?

I'm trying to read some.txt files and console.log an object with the formatted data after that, but idk how to do this with async/await. I tried this but then just got the error " SyntaxError: Unexpected reserved word "

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'];
        fs.readFile('./data txt/' + files[num], 'utf8', (err, data) => {
            if(err){
                console.log(err)
            }
            await test(obj, 'data', data) 
        });
};


parse(0); // need to end so that console.log() catch the new obj 
console.log(obj)

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));
        });
});

You can wrap the callback for fs.readFile in a Promise and then resolve or reject the results.

Wrap the call to parse() in an anonymous async function to be able to use await .

const 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'];
  return new Promise((resolve, reject) => {
    fs.readFile('./data txt/' + files[num], 'utf8', (err, data) => {
      if (err) {
        return reject(err);
      }
      return resolve(test(obj, 'data', data));
    });
  })
};

(async function() {
  const obj = await parse(0); // need to end so that console.log() catch the new obj 
  console.log(obj)
}());

/* 
// using thenables
parse(0).then((obj) => console.log(obj));
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM