2017-06-04 161 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