javascript 类型错误:任务不是异步 js 并行中的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33111961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:08:08  来源:igfitidea点击:

TypeError: task is not a function in async js parrallel

javascriptnode.jsasynchronousexpresscallback

提问by Bazinga777

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

我正在尝试使用以下代码上传图像并更新数据库集合中图像的 url。

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.

上传图像时出现以下错误,但图像已上传到服务器,其 url 也在数据库集合中更新。我假设它与我的回调有关,但我不确定我哪里出错了。任何有关如何调试的提示将不胜感激。

   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)

采纳答案by Kevin Leary

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

您还可以通过向 传递一个空对象来稍微简化一下bind()

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

回答by Explosion Pills

async.seriesand most of the asynccontrol flow functions expect functions or arrays of functions to be returned, e.g.

async.series并且大多数async控制流函数都期望返回函数或函数数组,例如

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

The return values of your two function calls, uploadImageand ProcessUploadare notfunctions. asyncerrors out.

你的两个函数的返回值调用uploadImage并且ProcessUpload没有的功能。async错误。

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