异步功能无法正常运行

时间:2013-12-12 10:35:06

标签: node.js express

我的快递代码在下面

我在做什么 ::

  1. 我正在重命名我在服务器上收到的图片的位置
  2. 我也在将图像名称更新为数据库
  3. 我正在同样地做这两件事
  4. 我正在使用async这个

  5. 我的问题 ::

    • 因此,程序中的异步有两个回调
    • 只有我的第一个回调功能有效,而另一个回调功能没有 工作
    • 虽然我已经完成了两个任务的完美定义,处理 他们一次,我无法解决它

    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'));
    
    });
    

    我该如何解决这个问题

    希望我很清楚

3 个答案:

答案 0 :(得分:1)

您需要调用传递给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);
      });
    }
  ]);
});

答案 1 :(得分:1)

请阅读有关Async系列方法(click here

的文档

为了移动到系列中的下一个函数,需要调用回调

async.series([
  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");
        }
        callback(null); // Pass whatever you think is appropriate
      });
    });
  },
  function(callback){
      connection.query('INSERT INTO ImagePostingTABLE (Image_Name) VALUES (?)', [file_name], function (err, rows, fields) {
          console.log('Connection result error ' + err);
          callback(err, rows)
        });
  }
]);

答案 2 :(得分:1)

C Blanchard&帮助下Bulkan .....我得到了解决方案


以下是完整的解决方案 :: This may help someone looking something similar

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");
              }

              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);
          });
        }
      ]);
    });

    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'));

    });