gpt4 book ai didi

node.js - 在下载模块中使用 promises

转载 作者:搜寻专家 更新时间:2023-10-31 23:54:43 25 4
gpt4 key购买 nike

我正在使用 bluebird 来实现 promise 。

我正在尝试 promise download module .

这是我的实现:

Promise  = require('bluebird'),
download = require('download');

var methodNameToPromisify = ["download"];

function EventEmitterPromisifier(originalMethod) {
// return a function
return function promisified() {
var args = [].slice.call(arguments);
// Needed so that the original method can be called with the correct receiver
var self = this;
// which returns a promise
return new Promise(function(resolve, reject) {
// We call the originalMethod here because if it throws,
// it will reject the returned promise with the thrown error
var emitter = originalMethod.apply(self, args);

emitter
.on("response", function(data) {
resolve(data);
})
.on("data ", function(data) {
resolve(data);
})
.on("error", function(err) {
reject(err);
})
.on("close", function() {
resolve();
});
});
};
};
download = { download: download };
Promise.promisifyAll(download, {
filter: function(name) {
return methodNameToPromisify.indexOf(name) > -1;
},
promisifier: EventEmitterPromisifier
});

然后使用它:

return download.downloadAsync(fileURL, copyTo, {});

我的问题是它没有下载所有文件(我有一个列表发送给这个函数),我做错了什么?

最佳答案

发射器确实会发射多个 数据事件,一个对应于它接收到的每个 block 。但是,a 仅代表一个 future 值,在您的情况下,您希望它是完整的响应。

resolve 应该只调用一次,用传递的值履行 promise ,然后结算。进一步的调用将无效 - 这就是为什么您只获得列表的第一部分的原因。

相反,您需要累积所有数据,当流结束时,您可以用所有数据履行 promise 。

var Promise  = require('bluebird'),
download = require('download'),
Buffer = require('buffer'); // should be global anyway

exports = {
downloadAsync: function promisifiedDownload() {
var args = arguments, self = this;

return new Promise(function(resolve, reject) {
// We call the originalMethod here because if it throws,
// it will reject the returned promise with the thrown error
var emitter = download.apply(self, args);
var buffers = [];

emitter.on("data", function(data) {
buffers.push(data);
}).on("error", function(err) {
reject(err);
}).on("close", function() {
resolve(Buffer.concat(buffers));
});
});
};
};

请注意,当您只想 promise 单个方法时,使用 promisifyAll 是非常荒谬的。为了简单起见,我省略了它

您可能还会监听传入的 response对象,并将 data 监听器直接附加到它。然后您可以使用 end event而不是 close

关于node.js - 在下载模块中使用 promises,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24920283/

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