Meteor:在从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/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你可以通过这个演示来学习如何使用它。
相关文章:
- Meteor方法在客户端返回null,在客户端运行的相同方法返回正确的值
- React+Meteor:this.ops返回未定义
- 无法在Meteor/MongoDB中返回当前用户对象
- Meteor.call()回调未向模板返回值
- 包含插入的Meteor方法没有返回记录ID作为结果
- Meteor js-控制台显示'未定义'即使返回结果
- Meteor 方法返回客户端和服务器上的不同对象
- 从Meteor.method中的回调返回值
- Meteor 方法返回未定义到客户端(异步)
- 为什么 Meteor.users.findOne({用户名: “test”}) 返回一个对象,但用具有相同值的变量替换
- 将 Meteor.setTimeout 返回值存储在 Collection 中
- this.userId 在 Meteor.publish 中返回未定义
- 通过 Meteor / Mongo 返回子文档数组
- Meteor.methods:从内部回调将数据返回给客户端
- 从 Meteor 中的 Stripe API 返回的 JSON 字典中的访问值
- 发布中的 Meteor find() 返回数据,尽管选择键为空
- 在方法中返回Meteor.http结果
- 不断调用/返回Meteor.method
- 如何从HTTP.call返回Meteor.JS中的值“;获取”;
- 返回Meteor中的数据问题