te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - TypeError: task is not a function in async js parrallel - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeError: task is not a function in async js parrallel - Stack Overflow

programmeradmin4浏览0评论

I am trying to upload an image and update the url of the image in the database collection using the code below.

Controller.prototype.handle = function (req, res, next) {
  var id = req.params.id,
      controller = req.params.controller,
      optionalController;

  optionalController = _.clone(controller);

  // handle optional controller
  if (controller === 'newboat') {
    controller = 'boat';
  } else if (controller === 'newcrew') {
    controller = 'crew';
  }

  var files = req.files.files || {},
      monthYear = new Date(),          
      monthYear = [monthYear.getFullYear(), monthYear.getMonth()],      
      filename = files[0].originalFilename,
      path = files[0].path,
      extension = filename.match(EXPRESSION_EXTENSION)[1],
      destFolder = [ROOT, monthYear[0], '/', monthYear[1] ].join(''),
      destination = [ROOT, monthYear[0], '/', monthYear[1] ,'/', id, '.', extension ].join('');      

  // log info  
  //console.log(id, controller, filename, extension, destination, path);

  var opts = JSON.stringify({id: id, photo: ['/uploads/',monthYear[0], '/', monthYear[1] ,'/', id, '.', extension ].join('') });

  async.series([
                uploadImage(path,destFolder,destination), 
                ProcessUpload(optionalController, opts, res) 
              ]);
};

// write file
var uploadImage = function(path,destFolder, destination) {
    // The land of callbacks ------>>>>>> inception within inception
    mkdirp(destFolder,777,function (err) {      
       fs.readFile(path, function (err, data) {
           fs.writeFile(destination, data, function (err) {
                if (err) {
                    console.log('image not uploaded..');
                    return false;
                }else {
                  return true;
                }
            });
        });
    }); 

};


var ProcessUpload = function(optionalController, opts, res ) {

  opts = JSON.parse(opts);

  if (optionalController === 'boat') {    
    updateBoatDatabase(opts);    
  }

};

/**
 * Update boat photo to database
 */
var updateBoatDatabase = function (opts, callback) {
  // save to database
  return dbServices.dbBoat.updatePhoto(opts, callback);
};

Here is the Database Service that is being called

  /**
   * Update image
   */
  updatePhoto: function (opts, callback) {
    var id = opts.id;

    // find boat by id
    this.modelClass.findById(id, function (err, model) {
      if (err || !model)
        return callback(err);      

      // set update value
      model.photo = opts.photo;

      // save
      model.save(callback);
    });
  },

I get the following error in uploading the image but the image gets uploaded on the server and its url updated on the database collection as well. I am assuming that it has to do with my callbacks but I am not really sure where I am going wrong. Any tips on how to debug this would be appreciated.

   TypeError: task is not a function
    at /home/work/bluewatertracks/node_modules/async/lib/async.js:689:13
    at iterate (/home/work/bluewatertracks/node_modules/async/lib/async.js:265:13)
    at async.forEachOfSeries.async.eachOfSeries (/home/work/bluewatertracks/node_modules/async/lib/async.js:284:9)
    at _parallel (/home/work/bluewatertracks/node_modules/async/lib/async.js:688:9)
    at Object.async.series (/home/work/bluewatertracks/node_modules/async/lib/async.js:710:9)
    at Controller.handle (/home/work/bluewatertracks/server/routers/photoUploader.js:56:9)
    at Layer.handle [as handle_request] (/home/work/bluewatertracks/node_modules/express/lib/router/layer.js:82:5)
    at next (/home/work/bluewatertracks/node_modules/express/lib/router/route.js:110:13)
    at Form.<anonymous> (/home/work/bluewatertracks/node_modules/connect-multiparty/index.js:101:9)
    at emitNone (events.js:72:20)
    at Form.emit (events.js:166:7)
    at maybeClose (/home/work/bluewatertracks/node_modules/connect-multiparty/node_modules/multiparty/index.js:557:10)
    at endFlush (/home/work/bluewatertracks/node_modules/connect-multiparty/node_modules/multiparty/index.js:552:3)
    at WriteStream.<anonymous> (/home/work/bluewatertracks/node_modules/connect-multiparty/node_modules/multiparty/index.js:617:5)
    at emitNone (events.js:72:20)
    at WriteStream.emit (events.js:166:7)

I am trying to upload an image and update the url of the image in the database collection using the code below.

Controller.prototype.handle = function (req, res, next) {
  var id = req.params.id,
      controller = req.params.controller,
      optionalController;

  optionalController = _.clone(controller);

  // handle optional controller
  if (controller === 'newboat') {
    controller = 'boat';
  } else if (controller === 'newcrew') {
    controller = 'crew';
  }

  var files = req.files.files || {},
      monthYear = new Date(),          
      monthYear = [monthYear.getFullYear(), monthYear.getMonth()],      
      filename = files[0].originalFilename,
      path = files[0].path,
      extension = filename.match(EXPRESSION_EXTENSION)[1],
      destFolder = [ROOT, monthYear[0], '/', monthYear[1] ].join(''),
      destination = [ROOT, monthYear[0], '/', monthYear[1] ,'/', id, '.', extension ].join('');      

  // log info  
  //console.log(id, controller, filename, extension, destination, path);

  var opts = JSON.stringify({id: id, photo: ['/uploads/',monthYear[0], '/', monthYear[1] ,'/', id, '.', extension ].join('') });

  async.series([
                uploadImage(path,destFolder,destination), 
                ProcessUpload(optionalController, opts, res) 
              ]);
};

// write file
var uploadImage = function(path,destFolder, destination) {
    // The land of callbacks ------>>>>>> inception within inception
    mkdirp(destFolder,777,function (err) {      
       fs.readFile(path, function (err, data) {
           fs.writeFile(destination, data, function (err) {
                if (err) {
                    console.log('image not uploaded..');
                    return false;
                }else {
                  return true;
                }
            });
        });
    }); 

};


var ProcessUpload = function(optionalController, opts, res ) {

  opts = JSON.parse(opts);

  if (optionalController === 'boat') {    
    updateBoatDatabase(opts);    
  }

};

/**
 * Update boat photo to database
 */
var updateBoatDatabase = function (opts, callback) {
  // save to database
  return dbServices.dbBoat.updatePhoto(opts, callback);
};

Here is the Database Service that is being called

  /**
   * Update image
   */
  updatePhoto: function (opts, callback) {
    var id = opts.id;

    // find boat by id
    this.modelClass.findById(id, function (err, model) {
      if (err || !model)
        return callback(err);      

      // set update value
      model.photo = opts.photo;

      // save
      model.save(callback);
    });
  },

I get the following error in uploading the image but the image gets uploaded on the server and its url updated on the database collection as well. I am assuming that it has to do with my callbacks but I am not really sure where I am going wrong. Any tips on how to debug this would be appreciated.

   TypeError: task is not a function
    at /home/work/bluewatertracks/node_modules/async/lib/async.js:689:13
    at iterate (/home/work/bluewatertracks/node_modules/async/lib/async.js:265:13)
    at async.forEachOfSeries.async.eachOfSeries (/home/work/bluewatertracks/node_modules/async/lib/async.js:284:9)
    at _parallel (/home/work/bluewatertracks/node_modules/async/lib/async.js:688:9)
    at Object.async.series (/home/work/bluewatertracks/node_modules/async/lib/async.js:710:9)
    at Controller.handle (/home/work/bluewatertracks/server/routers/photoUploader.js:56:9)
    at Layer.handle [as handle_request] (/home/work/bluewatertracks/node_modules/express/lib/router/layer.js:82:5)
    at next (/home/work/bluewatertracks/node_modules/express/lib/router/route.js:110:13)
    at Form.<anonymous> (/home/work/bluewatertracks/node_modules/connect-multiparty/index.js:101:9)
    at emitNone (events.js:72:20)
    at Form.emit (events.js:166:7)
    at maybeClose (/home/work/bluewatertracks/node_modules/connect-multiparty/node_modules/multiparty/index.js:557:10)
    at endFlush (/home/work/bluewatertracks/node_modules/connect-multiparty/node_modules/multiparty/index.js:552:3)
    at WriteStream.<anonymous> (/home/work/bluewatertracks/node_modules/connect-multiparty/node_modules/multiparty/index.js:617:5)
    at emitNone (events.js:72:20)
    at WriteStream.emit (events.js:166:7)
Share Improve this question asked Oct 13, 2015 at 20:24 Bazinga777Bazinga777 5,28113 gold badges56 silver badges94 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 11

async.series and most of the async control flow functions expect functions or arrays of functions to be returned, e.g.

async.series([
  function () {},
  function () {}
])

The return values of your two function calls, uploadImage and ProcessUpload are not functions. async errors out.

Instead you would have to write this as something like:

async.series([
    function (callback) {
        // callback has to be called by `uploadImage` when it's done
        uploadImage(path,destFolder,destination, callback);
    },
]);

You can also simplify this a bit by passing a null object to bind():

async.series( [
    uploadImage.bind( null, path, destFolder, destination ),
    ProcessUpload.bind( null, optionalController, opts, res )
] );
发布评论

评论列表(0)

  1. 暂无评论