gpt4 book ai didi

node.js - Bluebird 的适当 promise

转载 作者:太空宇宙 更新时间:2023-11-04 02:31:44 24 4
gpt4 key购买 nike

我有一个大致以下的代码(元CoffeeScript):

xml = new ...
Promise.promisifyAll xml

allRecords = []
xml.on 'frequentTag', (item) ->
...

iPromise = /* some promise made from item */

allRecords.push iPromise

xml.onAsync('end').then -> Promise.settle allRecords

现在的问题是:我可以摆脱 allRecords 累加器吗?

最佳答案

promise 代表一个单一值。这是一个值。

没有简单的方法来 promise 事件发射器,因为它不提供像单个值的 Node 样式回调这样的标准契约 - 因为不同的事件被多次调用。

EventEmitter 上执行 Promise.promisifyAll 本身不会产生有意义的结果,您必须手动 Promisify。好消息是,如果您碰巧经常这样做,您可以自己将其提取到函数中,或者使用 Bluebird 的 promisifyAll 和 promisifier 参数并让它为您执行遍历。

Bluebird 不了解您的事件发射器及其定义的有关何时调用回调以及如何调用的合约。假设它以 end 事件结束,带有 error 事件的错误数据会随着 frequentTag 事件流入 - 我会这样做:

xmlProto.prototype.getTags = function getTags(){
// if you do this very often, this can be faster
return new Promise(function(resolve, reject){
var results = [];
this.on("error", reject);
this.on("frequentTag", function(item){
iPhomise = /* some promise made from item */
results.push(iPromise);
});
this.on("end", resolve.bind(null, results));
}.bind(this)).settle(); // settle all
};

其中 xmlProto 是您新的的内容,这可以让您执行以下操作:

xml = new ...
xml.getTags().then(function(records){
// work with records
});

这可以提取到此类事件发射器的通用函数中 - 但您已经了解了总体思路。

关于node.js - Bluebird 的适当 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26090579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com