我正在尝试实现async / await模块。在function2中,如果用户不在,我想在那里停止执行。我不想执行功能3,如果用户在场,我想执行function3
const function1() {
//code
return a
}
const function2= (a,email) => model.user.findOne({ email:email}).then((user) => {
if (!user) {
****// want to stop execution here****
} else {
//update details of user
}
return dealer;
});
const function 3 = function(dealer) {
//mail sending
};
exports.mailer = async(email,callback) => {
try {
var a =await function1();
var dealer =await function2(a,email); //stop execution here
var res = await function 3(dealer);
await callback(res);
}catch (err){
callback(err);
}
}
答案 0 :(得分:2)
在function2中返回一个新的Promise,如果找到了一个用户就会解析,如果没有找到则拒绝你应该实现你想要的东西。 像这样:
const function1 = () => {
return a
}
const function2 = (a, email) => {
return new Promise((resolve, reject) => {
model.user.findOne({
email: email
}).then((user) => {
if (!user) {
// want to stop execution here****
reject(new Error('Error Message'))
} else {
// update details of user
resolve(dealer)
}
})
})
}
const function3 = (dealer) => {
//mail sending
}
exports.mailer = async (email, callback) => {
try {
var a = await function1()
var dealer = await function2(a, email) // stop execution here
var res = await function3(dealer)
await callback(res)
} catch (err) {
callback(err)
}
}