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