2017-06-04 7 views
1

コレクションに保存する前に画像をトリミングするコードがありますが、コードは非同期で実行されます。コレクションに挿入すると、イメージがトリミングされる前に実行されます。Meteorは関数を同期的に実行します

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番目の2.5Mbではありません。私は問題が何であるかわからない、私はエラーメッセージを見たことがない。私はちょうどイメージを取って比較する。 – andrey

関連する問題