【发布时间】:2016-01-10 14:31:47
【问题描述】:
当前版本的 Node.js 是否对 Promise 提供原生支持?
Node.js 使用 V8 引擎。 Chrome 也使用了这个 JavaScript 引擎,Chrome 32 原生支持 Promise。但我似乎无法获得在 Node.js 中(本地)工作的承诺。
我已经在 Chrome 32 中尝试了以下代码,它可以工作。
var promise = new Promise(function(resolve, reject) {
// do a thing, possibly async, then…
if ( 1===1 /* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
promise.then(function( message ) {
console.log( message );
},
function( err ) {
console.log( err );
});
但是,当我在 Node.js 中尝试相同的代码时,我得到:
var promise = new Promise(function(resolve, reject) {
^
ReferenceError: Promise is not defined
这段代码来自优秀的教程:
【问题讨论】:
-
Node 中的本机支持在所有模块都开始使用它之前并不是很有用。承诺一切。
-
@StevenLu:点击你的链接后我读到的第一件事:
BEWARE This article is old, it's 2013 old. Since then things have changed and a winner has prevailed, Bluebird is a Promises Library build with performance in mind and when actually tested with the benchmarks of this article it did even better than Async! -
请大家注意,Bluebird 声称是最快的已经有好几年了,它的速度声称基本上只是一个短路边缘情况,每次我亲自测试它时,它都有显然不是最快的。我个人使用 when.js 是因为它有很多让我的生活更轻松的功能,但碰巧的是,每次我进行性能比较时,它总是比 Bluebird 和 kew 快一点。唯一可以称为“慢”的库是 Q,它已经 4 年没有更新了。如果您选择速度,请先自己测试!
标签: javascript node.js promise