-1
我有一個簡單的Web應用程序,它登錄到我面向客戶的Web服務器並在獲取請求上下載日誌文件。當您向特定路由發送獲取請求時,模塊將啓動通過sftp連接到Web服務器並在本地下載日誌的2個獨立服務器。出於某種原因,我的鏈中的last then()方法在promise解決之前觸發。承諾在解決之前轉到下一個.then()?
router.js:
var express = require('express');
var router = express.Router();
var gather = require('../api/gather');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('home');
});
router.get('/api/gather',function(req,res,next){
console.log('sending web9 target');
gather.logs(['WEB9'])
.then((logsFound)=>{
console.log('sending web 11 target');
gather.logs(['WEB11',logsFound])
})
.then((logsFound)=>{
console.log(logsFound);
console.log('downloading finished rendering home with message');
res.render('home',{message: logsFound+' Log Files Ready for Pickup'});
})
.catch((e)=>{
res.render('home',{message: e});
});
});
module.exports = router;
/api/gather.js
//require ftp modules and define client
let Client = require('ssh2-sftp-client');
let sftp = new Client();
var fs = require('fs');
let sftp2 = new Client();
//set server configs
var boomeConfig = {
host: process.env.FTP_HOST,
port: process.env.FTP_PORT,
username: process.env.FTP_USER,
password: process.env.FTP_PASS
};
var webServerConfig = {
port: process.env.WEB_PORT,
username: process.env.WEB_USER,
password: process.env.WEB_PASS
};
let message;
const logDir = '/opt/foobar/logs/';
module.exports.logs = function(req, res){
console.log('hit gather module');
const target = req[0];
let logsFound = req[1] || 0;
return new Promise((resolve,reject)=>{
if(target === 'WEB9'){
webServerConfig.host = process.env.WEB9_HOST;
}else if(target === 'WEB11'){
webServerConfig.host = process.env.WEB11_HOST;
}else{
message = 'No Server Target Found';
resolve(message);
}
sftp.connect(webServerConfig)
.then(()=>{
return sftp.list(logDir);
})
.then((data)=>{
for(var i = 0; i < data.length; i++){
const remoteFileName = logDir + data[i].name;
const localFileName = './downloads/'+target+'/' + data[i].name;
//console.log('saving file '+localFileName);
sftp.get(remoteFileName).then((stream) => {
stream.pipe(fs.createWriteStream(localFileName));
});
}
console.log('Found '+data.length+' Logs on '+target);
sftp.end();
logsFound += data.length;
console.log('Got '+target+' Files Moving to next');
if(target ==='WEB11'){
console.log('Total count '+logsFound);
}
}).then((logsFound)=>{
resolve(logsFound);
})
.catch((e)=>{
console.log('error: '+e);
reject(e);
});
})
}
我家的路是越來越有logsFound呈現爲未定義。
我能想到的唯一的事情是,它可以在
sftp.get(remoteFileName).then((stream) => {
stream.pipe(fs.createWriteStream(localFileName));
});
仍然流文件時承諾解決。
是 「送網11目標」 的路徑文件記錄? –
是的,但它發生'下載完成渲染回家'消息'console.log –
你沒有給它一些等待。在幾個地方。如果你沒有從.then()返回一個承諾,它會繼續。 –