Meteor:在从Meteor.method返回之前,如何等待函数返回

Meteor: How do I wait on functions returning before returning from my Meteor.method?

本文关键字:返回 Meteor 等待 函数 何等待 在从 method      更新时间:2023-09-26

我有一个Meteor.method,它创建一个图像并编写css。我有一个微调器,它会一直显示到方法返回为止。该方法几乎在创建图像和css的函数完成任务之前立即返回。

如何在从Meteor.method返回之前包含一个回调以等待图像和css写入?

这是我的方法:

createImage: function(coords) {
   console.log('1: createImage')
   var source="myimage.png";
   var im = gm.subClass({imageMagick: true});
   im(source)
    .crop()
     .write('newimage.png', function(err){
       if (err) return console.dir(arguments)
        console.log('4: image has been written')
     }) // end of write function

 fs.appendFile(directory + 'css.import.less', css, function (err) {
   if (err) throw err;
   console.log('3: The "data to append" was appended to file!');
 });
  console.log('2: image and css written')
  return true;
},

我已经按照控制台日志的显示顺序对其进行了编号。我想要的是按照写入顺序显示console.log消息。

因此,取而代之的是:

//start of method
console.log('1: createImage')
console.log('4: image has been written')
console.log('3: The "data to append" was appended to file!');
console.log('2: image and css written')
//end of method

我期待这个:

//start of method
console.log('1: createImage')
console.log('2: image has been written')
console.log('3: The "data to append" was appended to file!');
console.log('4: image and css written')
//end of method

目前,该方法在编写图像和css的函数返回之前返回。这样做的效果是微调器显示一瞬间,而不是等到创建图像和css的函数返回,这意味着微调器应该显示更长的时间。

JS中有一个东西叫做Promises。http://www.html5rocks.com/en/tutorials/es6/promises/

我想这可能会帮你弄清楚。基本情况是这样的:

somePromiseShim(function(next) {
  console.log("first"); next();
}).then(function(data, next) {
  console.log("second"); next();
}).then(function(data, next) {
  console.log("third"); next();
});

你可能会问自己为什么要使用它——它有助于同步异步。因此,让我们在上面的代码中添加一些异步功能。

somePromiseShim(function(next) {
  console.log("first"); 
  setTimeout(function() { next(); }, 1000);
}).then(function(data, next) {
  console.log("second will fire up after 1 second"); next();
}).then(function(data, next) {
  console.log("third");
});

这里有一个我为朋友做的Promise的简单实现:https://gist.github.com/Schniz/0f525060aa9bec0b8d69你可以通过这个演示来学习如何使用它。