【问题标题】:What's the equivalent of jQuery.when() in nodejs?nodejs中jQuery.when()的等价物是什么?
【发布时间】:2014-10-10 13:03:51
【问题描述】:

我问过whats the equivalent of jquery when in angular,现在我想在节点中做类似的事情。我需要这样的东西:

when(fs.readFile('file1'), fs.readFile('file2')) .done(function( a1, a2 ) { ... // do stuff });

我怎样才能做到这一点?谢谢。

【问题讨论】:

    标签: node.js asynchronous stream promise fs


    【解决方案1】:

    您需要节点 0.11.13 或更高版本才能工作或使用库,但那将是 Promise.all:

    var Promise = require("bluebird"); // Imports the Bluebird promise library in 
                                       // new versions of node this is optional
    
    Promise.promisifyAll(fs); // this is required if using Bluebird, you'll have to 
                              // do this manually with native promises.
    Promise.all([fs.readFileAsync('file1'), fs.readFileAsync('file2')])
    .spread(function( a1, a2 ) {
       ... // do stuff
    });
    

    关于如何将回调 API 转换为 Promise - 请参阅 this question and answer

    【讨论】:

    • @LeonidBeschastny 没错,但在新版本的节点承诺中,作为 Node 的一部分发布,因为它们已被新的 JavaScript 标准所接受。在节点 0.12 中,promise 将开箱即用。 Bluebird 尤其适用于 Netscape 7,因此 Node 0.8 并不是一个真正的挑战 :)
    • Promise 适用于任何 node.js 版本,或者至少从 0.8.x 开始。
    • 我们的 cmets 是如何倒转的:S?
    • 我不小心删除了我的评论。
    • 感谢@BenjaminGruenbaum,非常详细!
    猜你喜欢
    • 2014-10-09
    • 1970-01-01
    • 2014-07-27
    • 2018-10-24
    • 2015-10-03
    • 2021-08-14
    • 2014-05-08
    • 2014-06-12
    • 1970-01-01
    相关资源
    最近更新 更多