0

getURL do return a promise object, why does not work?

const fs = require('fs');

function getURL(URL){
    fs.readFile(URL,(err, buffer)=>{
        if(err) return Promise.reject(err.message);
        return Promise.resolve(buffer.toString());
    });
    // return Promise.resolve(42); works
}
getURL('1.txt').then(text=>{
    console.log(text);
}).catch(err=>{
    console.log(err);
});

Thanks. Can I use static method Promise.resolve other than return new Promise object?

sfy
  • 2,810
  • 1
  • 20
  • 22

1 Answers1

1

You can't return a value from an asynchronous callback.

Instead, you need to create the promise in the outer function (with new Promise), and run your asynchronous code inside the executor of that promise:

function getURL(URL) {
  return new Promise((resolve, reject) => {
    // run asynchronous code here
    // call resolve on success or reject on error

    fs.readFile(URL, (err, buffer) => {
      if(err)
        reject(err);
      else
        resolve(buffer.toString());
    });
  }
}

That being said, it's considered best to avoid creating promises yourself whenever you can (as aaaaaa pointed out, it is a promise antipattern). In the specific case of fs (and other built-in Node modules) I'd recommend that you instead use something like mz, which wraps all built-in modules and makes them use promises instead of callbacks:

const fs = require('mz/fs');
function getURL(URL) {
  return fs.readFile(URL)
    .then((buffer) => buffer.toString());
}

// or even better:
function getURL(URL) {
  return fs.readFile(URL, 'utf8');
}
Frxstrem
  • 38,761
  • 9
  • 79
  • 119