0

为什么当我执行此代码列表为空时,我的异步调用是否不正确?我一直在移动东西并将它们分成功能,但在我的执行之间仍然存在竞争。

我想要执行的顺序是在它们的嵌套中,但我猜有些地方是错误的,因为它不起作用。

server.route({
  method: 'POST',
  path: '/convert',
  config: {
     validate: {
          payload: {
              fileUpload: Joi.object({
                  headers: Joi.object({
                      'content-type': Joi.string().valid(['application/pdf']).required(),
                  }).unknown().required()
              }).unknown()
          }
      },
       payload: {
         output: 'file',
         maxBytes: 209715200,
         uploads:'./thumbs'
       },
    handler: function(request, reply) {
      var newPath,
        filename,
        filenamePng;

      fs.readFile(request.payload.fileUpload.path, function(err, data) {
           filename = request.payload.fileUpload.filename;
           filenamePng = filename.substr(0, filename.indexOf('.'));
           newPath = __dirname + "/thumbs/";

            fs.writeFile(newPath + filename, data, function(err) {
                  ChildProcess.exec('cd ' + newPath + ' && convert ' + filename + ' -thumbnail 50% ' + filenamePng + '_thumb_page_' + '%d' + '.png', function(error) {
                        fs.readdir(__dirname + "/thumbs", function(error, list) {
                            list.forEach(function(element) {
                                 element = element.toString();
                                 Thumbs.addThumbnail(Thumbs.thumbnailArray, {name: element, url: './thumbs/' + element });
                            });
                           var tmpFN = request.payload.fileUpload.path;
                           fs.unlink(tmpFN, function(err){
                             if(err){
                                console.log(err);
                             }
                             else {
                                console.log('/tmp/file deleted')
                              //   reply(Thumbs.showThumbnails(Thumbs.thumbs));
                             };
                           });
                           reply(Thumbs.showThumbnails(Thumbs.thumbs));
                        });
                  });
            });

           process.on('exit', function(code) {
             console.log('PROCESS FINISHED');
           });

      });
    }
  }
});
4

1 回答 1

1

你应该完全使用异步(https://github.com/caolan/async),它有几种处理异步调用的方法,瀑布看起来对你的问题有好处:

async.waterfall([
  function(callback){
    callback(null, 'one', 'two');
  },
  function(arg1, arg2, callback){
    // arg1 now equals 'one' and arg2 now equals 'two'
      callback(null, 'three');
  },
  function(arg1, callback){
      // arg1 now equals 'three'
      callback(null, 'done');
  }
], function (err, result) {
  // result now equals 'done'    
});
于 2014-11-11T03:31:29.060 回答