2017-06-04 163 views
1

我有代码在裁剪图像之前将其保存到集合,但代码异步执行。在图像被裁剪之前插入到集合执行。流星执行功能同步

Meteor.methods({ 
    'createWorkout': function(workoutFormContent, fileObj) { 
     // crop image to width:height = 3:2 aspect ratio 
     var workoutImage = gm(fileObj.path); 
     workoutImage.size(function(error, size) { 
      if (error) console.log(error); 
      height = size.height; 
      width = size.height * 1.5; 
      workoutImage 
       .gravity("Center") 
       .crop(width, height) 
       .write(fileObj.path, function(error) { 
        if (error) console.log(error) 
       }); 
     }); 

     // add image to form content and insert to collection  
     workoutFormContent.workoutImage = fileObj; 
     Workouts.insert(workoutFormContent, function(error) { 
      if (error) { 
       console.log(error); 
      } 
     }); 
    }, 
}); 

如何能够同步运行此代码以便能够插入已裁剪的图像?

+0

你需要在回调中运行它。 – SLaks

回答

1

写入采集图像裁剪后,才:

import { Meteor } from 'meteor/meteor'; 
import gm from 'gm'; 
const bound = Meteor.bindEnvironment((callback) => {callback();}); 
Meteor.methods({ 
    createWorkout(workoutFormContent, fileObj) { 
    // crop image to width:height = 3:2 aspect ratio 
    const workoutImage = gm(fileObj.path); 
    workoutImage.size((error, size) => { 
     bound(() => { 
     if (error) { 
      console.log(error); 
      return; 
     } 

     const height = size.height; 
     const width = size.height * 1.5; 
     workoutImage.gravity('Center').crop(width, height).write(fileObj.path, (writeError) => { 
      bound(() => { 
      if (writeError) { 
       console.log(writeError); 
       return; 
      } 
      // add image to form content and insert to collection 
      workoutFormContent.workoutImage = fileObj; 
      Workouts.insert(workoutFormContent, (insertError) => { 
       if (insertError) { 
       console.log(insertError); 
       } 
      }); 
      }); 
     }); 
     }); 
    }); 
    } 
}); 

或者使用Fibers/Future lib下,它可以用来阻止事件循环。

+0

我试过这个解决方案,它不工作。流星抱怨说功能应该在光纤中运行。 – andrey

+0

@andrey请参阅我的更新回答 –

+0

此变体正在工作,但时间与时间。对于小图像它的作品,但对于大 - 没有。我测试了2张图片。第一个图像510Kb裁剪,但第二个2.5Mb - 不是。我不知道最新的问题,我没有看到任何错误消息。我只是拍摄一张照片并进行比较。 – andrey