[英]Non-blocking code execution
我有一个定义某些方法的Meteor项目。 在那些电子邮件中,发送电子邮件。 由于这会花费大量时间,并且会降低最终用户的整体使用效率,因此我想异步发送电子邮件。 电子邮件是否发送成功对方法调用的结果没有影响。
从我发现的结果来看,使用setTimeout
模拟异步调用是很常见的。 我也是在这种情况下应该做的吗?
编辑:注释中要求的代码
export const UpdateMaterial = new ValidatedMethod({
name: 'material.update',
validate: new SimpleSchema({
id: {type: String},
description: {type: String},
}).validator(),
run({id, description}){
const _id = new Meteor.Collection.ObjectID(id);
let res;
if(Meteor.isServer) {
res = Materials.update({_id}, {
$set: {
'metadata.description': description
}
});
}
SendHTMLEmailToRoles(Titles.NewMaterial,Texts.NewMaterial, [Roles.Admin]);
return res;
}
});
export const SendHTMLEmailToRoles = (subject,html,roles) => {
if(Meteor.isServer) {
const users = Meteor.users.find({role: {$in: roles}}).fetch();
const addresses = users.map(function(user){
if(!user.emails)
return;
return user.emails.pop().address;
});
Email.send({
to: addresses,
from: 'test@test.com',
subject,
html
});
}
}
如果我的理解是正确的,那么您显示的整个代码都是Meteor方法?
在这种情况下,调用它根本不会阻塞客户端,因为所有Meteor调用都是异步的。 这就是为什么您可以提供回调。
但是,如果没有精心设计,服务器上的Meteor方法是同步的。 因此,如果客户端进行进一步的呼叫,则在实际发送电子邮件之前,将不会处理这些呼叫。
要在服务器上恢复一些异步行为以发送电子邮件,请注意Sergio( https://docs.meteor.com/api/email.html )提供的参考页示例中的this.unblock()
行。
现在,如果您希望立即执行Meteor呼叫客户端回调,而不必等待Email.send()
完成,则必须延迟该指令(通常通过确实用setTimeout
包装)以让您的Meteor方法返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.