我有以下代码但是当调用resolve时它会抛出:
Possibly unhandled Error: undefined
at Promise$_rejecter (c:\projects\Test\promiseftp\node_modules\bluebird\js\main\promise.js:602:58)
at WriteStream.<anonymous> (c:\projects\Test\promiseftp\index.js:45:33)
at WriteStream.EventEmitter.emit (events.js:117:20)
at fs.js:1598:14
at Object.oncomplete (fs.js:107:15)
以下代码:
var Client = require('ftp');
var path = require('path');
var fs = require('fs');
var Promise = require('bluebird');
var c = new Client();
var connectionProperties = {
host: "myhost",
user: "myuser",
password: "mypwd"
};
c.connect(connectionProperties);
var downloadFiles = new Promise.method(function () {
return new Promise(function (reject, resolve) {
c.on('ready', function () {
c.list(function (err, list) {
if (err) reject(err);
list.forEach(function (element, index, array) {
//Ignore directories
if (element.type === 'd') {
console.log('ignoring directory ' + element.name);
return;
}
//Ignore non zips
if (path.extname(element.name) !== '.zip') {
console.log('ignoring file ' + element.name);
return;
}
c.get(element.name, function (err, stream) {
if (err) reject(err);
console.log(element.name);
stream.once('close', function () {
//c.end();
//resolve();
});
var pipeaction = stream.pipe(fs.createWriteStream(element.name));
pipeaction.on('close', function () {
console.log('close');
//THROWS HERE!
resolve();
});
});
});
});
});
});
});
downloadFiles().then(function () {
console.log('woot');
});
任何想法为什么?
答案 0 :(得分:3)
请不要混淆回调和承诺,看看它有多简单:
when(c, "ready").then(function(){
return c.listAsync();
}).filter(function(element) {
return element.type !== "d" && path.extname(element.name) === ".zip";
}).map(function(element) {
return c.getAsync(element.name).then(function(stream) {
return when(stream.pipe(fs.createWriteStream(element.name)), "close");
})
}).then(function(){
console.log("all files copied");
});
样板:
var path = require('path');
var fs = require('fs');
var Promise = require('bluebird');
var Client = require('ftp');
Promise.promisifyAll(Client.prototype);
var c = new Client();
var connectionProperties = {
host: "myhost",
user: "myuser",
password: "mypwd"
};
c.connect(connectionProperties);
function when(obj, event) {
return new Promise(function(resolve) {
obj.on(event, resolve);
});
}
答案 1 :(得分:0)
我终于开始工作并在博客中发布了结果 - http://blog.jonathanchannon.com/2014/03/22/using-node-and-ftp-with-promises/