javascript - 为什么 NodeJS 不将 Promise 用于 readFile API?

标签 javascript node.js asynchronous promise nonblocking

在书中https://pragprog.com/book/tbajs/async-javascript ,我发现了这个:

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.”

我看起来很困惑,因为作为读取文件的 API,这个

fs.readFile('/etc/passwd')
.onSuccess(function(data){console.log(data)})
.onError(function(err){throw err})

看起来比这好多了:

fs.readFile('/etc/passwd', function (err, data) {
  if (err) throw err;
  console.log(data);
});

有没有人知道为什么“Promises 是一个更高级别的构造”会阻止自己在 NodeJS API 中使用?

最佳答案

Node v8 附带 util.promisify,可将回调 API 转换为 Promise,Node v10 附带原生 Promise 支持(实验性):

const fs = require('fs').promises;

// in an async function:
let data = await fs.readFile('/etc/passwd');
console.log(data);

future 就是 promise :

NodeJS 为新的 API 使用 Promise。事实上,目前正在讨论如何。由于摩擦和性能问题,几年前在 0.2 中使用 Node 中的 Promises 的早期尝试失败了。

首先要做的事情:

现在 Promise 是一种本地语言功能,但在将其用于核心 API 之前必须进行以下操作:

  • Promise 必须是母语结构这已经发生了。
  • 最近宣布的 NodeJS 和 io.js 合并必须发生 - 时间框架可能是短短几个月。
  • v8(JavaScript 引擎)团队必须完成私有(private)符号的工作,这将能够快速创建 Promise。目前,Promise 构造函数是在原生 Promise 中创建 Promise 的唯一方法,它分配了一个相对昂贵的闭包。目前,Domenic 正在 io.js 和 v8 团队之间密切协调,以确保正确完成这项工作。
  • v8 团队必须优化 Promise 实现,目前原生 Promise 始终输给 Bluebird 等用户态实现。现在也在发生这种情况。

一旦所有这些发生,API 将被 fork ,并且包含 Promise 的版本将被集成到核心中。 Here is a long and uninteresting discussion关于它 - 在 io.js/NG 存储库中有一个更好的,但两者都不是太丰富。

今天可以做什么

等库给你即时工具convert a callback API to promises以快速有效的方式。您现在可以使用它们并获得该功能。

关于javascript - 为什么 NodeJS 不将 Promise 用于 readFile API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30299613/

相关文章:

javascript - 如何向非 cocoa 应用程序添加 AppleScript/JXA 支持?

javascript - 如何访问其他同级文件夹的 package.json 或组织 MERN 堆栈的文件夹

javascript - 只用JS解析JS

javascript - Kendo 网格 - 如何通过 UP/DOWN 键盘键使整行选择可导航?

javascript - jQuery:选择样式属性?

node.js - Laravel 5 使用 Node 和 Laravel-Echo-Server 将事件广播到 WildCard channel

node.js - Azure Functions : Nodejs, 使用文件系统时有哪些限制/限制?

javascript - 使用 React 的 RSS 解析器在页面刷新时失败

swift - 如何从 firebase 异步加载数据并将其显示在 UICollectionView 中

javascript - Rails 中的 Jquery 异步表单提交