0

In the code below the function, readFileAsync() is used to read a file and return a new Promise. It doesn't throw an error but it may not be structured properly.

function readFileAsync(filename) {
    return new Promise( (resolve, reject) => {
        fs.readFile((path.join(__dirname, filename)), { encoding: 'utf-8' }, (err, data) => {
            if(err) {
                reject(err);
            } else {
                resolve(data);
            }
        });
    });
}

console.log(readFileAsync('/helperData/jsonFormat.txt'));

Question: How do I structure this example to use .then() and .catch()? No matter where I locate these (inside or outside the function) it throws an exception. I feel like I might have coded myself into a corner and I'm not sure how this pattern needs to be laid out.

Ani Menon
  • 27,209
  • 16
  • 105
  • 126
  • 1
    Your `readFileAsync` is right - it returns a Promise when called, so to get the resolved value, call `.then` on its call (and to catch errors, call `.catch` on its call) eg `readFileAsync(...).then(console.log).catch((err) => /* handle err */)` – CertainPerformance Aug 16 '19 at 23:19
  • 1
    Oh, one thing, change `reject(Error, err);` to `reject(err)` – CertainPerformance Aug 16 '19 at 23:23
  • Thanks CertainPerformance, I've tried that pattern but it also throws an exception. `ReferenceError: data is not defined`, `readFileAsync('/helperData/jsonFormat.txt').then( console.log(data) ).catch();` – stackedAndOverflowed Aug 16 '19 at 23:24
  • instead of function declaration, try : `var readFileAsync = new Promise(....) ` Then you can do `readFileAsync.then()` – rocketTheCat Aug 16 '19 at 23:25
  • @MichelleDai The function form is a *lot* more flexible than just declaring a Promise, though – CertainPerformance Aug 16 '19 at 23:25
  • 2
    `.then` accepts a *function* as a parameter, not plain code lines - either `.then(console.log)` or `.then((data) => console.log(data))` – CertainPerformance Aug 16 '19 at 23:27
  • @CertainPerformance how about instead of function declaration, try function expression for `var readFileAsync = .... function that will return a Promise`. Then `readFileAsync.then()` and `.catch()` after that block code – rocketTheCat Aug 16 '19 at 23:29
  • @techieWannabe Function declaration vs expression makes no difference in this case. Since `readFileAsync` will be a function, have to call it, not just reference it, to get a Promise from it - `readFileAsync(...).then(...`, not just `readFileAsync.then(...` – CertainPerformance Aug 16 '19 at 23:30
  • I just wanted to say I've ready through all these comments and I've got it working. Understanding that I was passing a function to .then() and not just a simple parameter makes it all make sense. Thanks! – stackedAndOverflowed Aug 16 '19 at 23:41

0 Answers0