Javascript Meteor同步执行函数

Javascript Meteor同步执行函数,javascript,meteor,Javascript,Meteor,我有一段代码,在将图像保存到集合之前裁剪图像,但代码是异步执行的。在裁剪图像之前执行“插入到集合” Meteor.methods({ 'createWorkout': function(workoutFormContent, fileObj) { // crop image to width:height = 3:2 aspect ratio var workoutImage = gm(fileObj.path); workoutImage

我有一段代码,在将图像保存到集合之前裁剪图像,但代码是异步执行的。在裁剪图像之前执行“插入到集合”

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

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

仅在图像裁剪后写入集合:

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,它可以用来阻止事件循环。

您需要在回调中运行它。我已经尝试了这个解决方案,但它不起作用。Meteor抱怨说,该功能应该在光纤中运行。该变体正在工作,但有时会出现。对于小图像,它是有效的,但对于大图像,它不是。我已经测试了2个图像。第一个图像被裁剪了510Kb,但第二个图像被裁剪了2.5Mb—没有。我不知道是什么问题,我没有看到任何错误消息。我只是拍了一张照片比较一下。看起来这不是你们提供的解决方案的问题,而是裁剪的问题。我试着只裁剪图片,而大的图片并没有被裁剪。我检查你的建议作为解决方案。@andrey这是我们的建议,看一看,应该能帮你解决这个问题,这就是我要找的!但我不只是制作一个缩略图,我想把图像裁剪成3:2的纵横比。我上面提到的错误是因为我使用了错误的逻辑,并试图在新的预期尺寸时裁剪已经更短的图像。例如,如果图像w:1999 h:1444,我将最短边作为宽度,并尝试使宽度符合3:2宽高比w=1444x1.5=2166,这比1999大,因此这是不可能的。为了实现我的目标,我必须处理好几种变体。