In the book https://pragprog.com/book/tbajs/async-javascript, I found this:
Node’s early iterations used Promises in its nonblocking API. However, in February 2010, Ryan Dahl made the decision to switch to the now-familiar callback(err, results...) format, on the grounds that Promises are a higher-level construct that belongs in “userland.”
It looks quite confusing to me, because as an API to read files, this
fs.readFile('/etc/passwd')
.onSuccess(function(data){console.log(data)})
.onError(function(err){throw err})
looks much better than this:
fs.readFile('/etc/passwd', function (err, data) {
if (err) throw err;
console.log(data);
});
Does anyone have ideas about why "Promises are a higher-level construct" will stops itself from being used in NodeJS API?
Node v8 ships with util.promisify
that converts callback APIs to promises, Node v10 ships with native promises support (experimental):
const fs = require('fs').promises;
// in an async function:
let data = await fs.readFile('/etc/passwd');
console.log(data);
NodeJS will use promises for the new APIs. In fact it is currently discussed how. An earlier attempt in 0.2 to use Promises in node years ago failed because of friction and performance issues.
Now promises are a native language feature, but the following has to happen before they make it to the core APIs:
Once all these happen the API will be forked and a version containing promises will be integrated into core. Here is a long and uninteresting discussion about it - there is a better one at the io.js/NG repo but neither are really too informative.
Libraries like bluebird give you tools to instantly convert a callback API to promises in a fast and efficient way. You can use them today and get that functionality.
Update 2018 / Node 10: New fs.promises API
The fs.promises API provides an alternative set of asynchronous file system methods that return Promise objects rather than using callbacks. The API is accessible via require('fs').promises.
https://nodejs.org/api/fs.html#fs_fs_promises_api
(experimental at this moment, but working perfectly on node latest)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With