Hapijs,fs.readfile,fs.writefile和childprocess.exec如何控制我的异步?

时间:2014-11-11 01:05:06

标签: javascript node.js asynchronous hapijs

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

我希望执行的顺序是在它们的嵌套中,但我猜错了,因为它不起作用。

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

      });
    }
  }
});

1 个答案:

答案 0 :(得分:1)

你应该完全使用async(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'    
});