gpt4 book ai didi

javascript - 从另一个文件调用函数并在完成后获取结果?

转载 作者:行者123 更新时间:2023-12-01 00:45:15 25 4
gpt4 key购买 nike

如果第一个函数完成并返回 true,从另一个文件调用函数然后执行其他操作的最佳方法是什么?

module.exports = {
sendEmail: function(user, subject, text) {
var smtpTransport = nodemailer.createTransport({
service: 'gmail',
auth: {
user: config.email,
pass: config.gmlpwd
}
});
var mailOptions = {
to: user,
from: config.email,
subject: subject,
text: text
};
smtpTransport.sendMail(mailOptions, function(err) {
return true
});
}
}
mailer.sendEmail(user.email, subject, text, function(){
//do something here if the function is done successfully, but it never gets called
});

最佳答案

sendMail 函数中,您需要添加该回调作为参数,然后在完成后调用它。

module.exports = {
sendEmail: function(user, subject, text, cb) {
var smtpTransport = nodemailer.createTransport({
service: 'gmail',
auth: {
user: config.email,
pass: config.gmlpwd
}
});
var mailOptions = {
to: user,
from: config.email,
subject: subject,
text: text
};
smtpTransport.sendMail(mailOptions, function(err) {
return cb(err);
});
}
}
mailer.sendEmail(user.email, subject, text, function(){
// do something here
});

但是,重复执行此操作可能会导致您进入 callback hell ,我建议考虑使用 Promise 或 RxJS 来代替。

关于javascript - 从另一个文件调用函数并在完成后获取结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57443345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com