Why does NodeJS NOT use Promise for the readFile API?

六眼飞鱼酱① 提交于 2020-06-10 02:56:27

问题


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?


回答1:


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

The future is promises:

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.

What has to happen first:

Now promises are a native language feature, but the following has to happen before they make it to the core APIs:

  • Promises have to be a native language construct this already happened.
  • The NodeJS and io.js merger that was recently announced has to happen - the time frame is a few short months probably.
  • The v8 (JavaScript engine) team has to finish working on private symbols which will enable fast promise creation. At the moment the promise constructor is the only way to create promises in native promises and it allocates a closure which is relatively expensive. This is currently being done with Domenic working in tight coordination between the io.js and v8 team to ensure this is done properly.
  • The v8 team has to optimize the promise implementation, currently native promises lose consistently to userland implementations like bluebird. This is also happening now.

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.

What can be done today

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.




回答2:


Historically callbacks are the default for performance reasons, but...

Update 2017 / Node 8: Promises are now supported by the core!

Node.js supports promises since Node v8.x. The APIs are all still written in callback style (for backwards compatibility etc.), but there now is a utility class in node core to convert the callback-based APIs to promise-based APIs (similarly to bluebird):

https://nodejs.org/api/util.html#util_util_promisify_original

From the Node.js docs:

For example:

const util = require('util');
const fs = require('fs');

const stat = util.promisify(fs.stat);
stat('.').then((stats) => {
  // Do something with `stats`
}).catch((error) => {
  // Handle the error.
});

Or, equivalently using async functions:

const util = require('util');
const fs = require('fs');

const stat = util.promisify(fs.stat);

async function callStat() {
  const stats = await stat('.');
  console.log(`This directory is owned by ${stats.uid}`);
}



回答3:


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)




回答4:


Promises is a library, when using promise it requires to return Promise constructor from function but using callback function chaining same thing is achievable that's why "Promises are a higher-level construct"

Reference: Promises in node js



来源:https://stackoverflow.com/questions/30299613/why-does-nodejs-not-use-promise-for-the-readfile-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!