我在下面有我的快递代码
我在做什么::
我正在重命名服务器上收到的图像的位置
我还将图像的名称更新为数据库
我同时做这两件事
我为此使用异步
我的问题::
所以程序中有两个异步回调
只有我的第一个回调功能有效,而另一个则无效
工作中
尽管我已经定义了两个任务,但仍然可以很好地处理
他们一次,我无法解决它
app.js
var express=require('express');
var fs=require('fs');
var http=require('http');
var crypto=require('crypto');
var mysql=require('mysql');
var async=require('async');
var app=express();
var connection=mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'ImagePostingDB'
});
connection.connect();
app.set('port',process.env.PORT||7002);
app.use('/Details',express.static(__dirname+'/public/images'));
app.use(express.bodyParser());
app.post('/Details/',function(req,res,next)
{
var file_name=req.files.key.originalFilename;
console.log(file_name);
async.series( [
// Get the first table contents
function ( callback )
{
crypto.randomBytes(8, function(ex, buf) {
var array = req.files.key.originalFilename.split('.');
var type = array[array.length - 1];
var name = buf.toString('hex') + '.' + type;
fs.rename(req.files.key.path, './public/images/' + name, function(e) {
if (e) {
res.send(500, e.message);
} else
{
res.send("I got the message - This i confirm");
}
});
});
},
// Updating the database
function ( callback )
{
connection.query('INSERT INTO ImagePostingTABLE (Image_Name) VALUES (?)', [file_name], function (err, rows, fields)
{
console.log('Connection result error ' + err);
});
}
] );
});
app.get('/Details/',function(req,res){
res.send("Image displayed");
});
http.createServer(app).listen(app.get('port'),function(){
console.log('Express server listening on port'+app.get('port'));
});
我该如何解决
希望我清楚
最佳答案
您需要调用传递到callback
任务功能的async.series
这是代码
app.post('/Details/',function(req,res,next) {
var file_name=req.files.key.originalFilename;
console.log(file_name);
async.series( [
// Get the first table contents
function ( callback ) {
crypto.randomBytes(8, function(ex, buf) {
var array = req.files.key.originalFilename.split('.');
var type = array[array.length - 1];
var name = buf.toString('hex') + '.' + type;
fs.rename(req.files.key.path, './public/images/' + name, function(e) {
if (e) {
res.send(500, e.message);
} else {
res.send("I got the message - This i confirm");
}
return callback(null);
});
});
},
// Updating the database
function ( callback ) {
connection.query('INSERT INTO ImagePostingTABLE (Image_Name) VALUES (?)', [file_name], function (err, rows, fields) {
console.log('Connection result error ' + err);
return callback(null);
});
}
]);
});