![](/img/trans.png)
[英]How to wait for sub process results before returning from Meteor.method
[英]Meteor: How do I wait on functions returning before returning from my Meteor.method?
我有一个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/zh-CN/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您可能会在此演示中学习如何使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.