我对节点很新,并且遇到了顺序运行某些函数和使用回调的问题。我曾尝试使用异步模块,但是,我认为我错过了一些东西,因为它使我的功能无序。
用最简单的术语我想以url params的形式检索一些数据,然后: 1.将它们写入文件 2.打印它们 3.删除文件
我的当前代码在打印之前删除文件。在步骤2之前的第3步。是否有人会就如何按顺序执行这些操作提供一些建议?提前谢谢。
router.get('/zplprint/:barcode/:zpl', function(req, res) {
var zpl = req.params.zpl;
var filename = appDir + "/uploads/" + req.params.barcode + ".zpl";
console.log(req.params.zpl);
res.send("received zpl: " + req.params.zpl);
async.series([
function(callback){
fs.writeFile(filename, zpl, function(err) {
if(err) {
callback(err);
return;
}
console.log("The file was saved! to "+filename);
callback();
});
},
function(callback){
CupsPrinterName = nconf.get('Print:PrinterName');
console.log(CupsPrinterName);
var cmd = 'lpr -P ' + CupsPrinterName + ' -o raw ' + filename;
exec(cmd, function(error, stdout, stderr) {
// command output is in stdout'
console.log(cmd);
console.log("file printed");
});
callback();
},
function(callback){
fs.unlink(filename, function (err) {
console.log(' deleting ' + filename);
});
callback();
}
]);
});
答案 0 :(得分:0)
您在callback()
的同一级别调用exec()
函数,exec是异步的,并且将记录"文件打印"删除文件后,因为callback()是在exec()
之外调用的,而不是在函数结束时调用的。打印后尝试调用回调:
function(callback){
CupsPrinterName = nconf.get('Print:PrinterName');
console.log(CupsPrinterName);
var cmd = 'lpr -P ' + CupsPrinterName + ' -o raw ' + filename;
exec(cmd, function(error, stdout, stderr) {
// command output is in stdout'
console.log(cmd);
console.log("file printed");
callback();
});
},
答案 1 :(得分:0)
var Q = require('q')
router.get('/zplprint/:barcode/:zpl', function(req, res) {
var zpl = req.params.zpl;
var filename = appDir + "/uploads/" + req.params.barcode + ".zpl";
console.log(req.params.zpl);
res.send("received zpl: " + req.params.zpl);
function first(callback){
var d1 = Q.defer();
fs.writeFile(filename, zpl, function(err) {
if(err) {
d1.reject(err);
}
console.log("The file was saved! to "+filename);
d1.resolve("success");
});
return d1.promise
}
function second(callback){
var d2 = Q.defer()
CupsPrinterName = nconf.get('Print:PrinterName');
console.log(CupsPrinterName);
var cmd = 'lpr -P ' + CupsPrinterName + ' -o raw ' + filename;
exec(cmd, function(error, stdout, stderr) {
if(error){
d2.reject()
}
console.log(cmd);
console.log("file printed");
d2.resolve()
});
return d2.promise
}
function third(callback){
var d3 = Q.defer()
fs.unlink(filename, function (err) {
if(err){
d3.reject()
}
console.log(' deleting ' + filename);
d3.resolve()
});
return d3.promise
}
first().then(second).then(third).fail(function(){
console.log("Error !!!!")
})
});
先决条件:
npm install q
最好的承诺结构