发射器确实发射multiple数据事件,每个接收到的数据块都有一个。然而,a仅代表one未来值,在您的情况下,您希望这是完整的响应。
resolve
应该只被调用一次,以用传递的值履行承诺,然后解决。进一步的调用将不会产生任何效果 - 这就是为什么您只获得列表的第一部分。
相反,您需要积累所有数据,当流结束时,您可以用所有数据履行承诺。
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));
});
});
};
};
Notice it's quite nonsensical to use promisifyAll
when you only want to promisify a single method. I've omitted it for simplicity
您还可以监听传入的response对象,并附加data
直接监听它。然后您可以使用end event代替close
.