我想使用findOne
的结果作为if
语句的条件。我不能返回true
或false
,我看到async
函数不同,但尽管尝试了几次,都没有成功。
Controller.js
// Find a single User with a sub
exports.findOne = (req, res) => {
const sub = req.params.sub;
User.findOne({sub})
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message: "Error retrieving User with sub=" +sub
});
});
};
前端:
//INFO SAVE AND UPDATE CONDITION
async function exist() {
let x = await InfoDataService.get(data.sub)
console.log(x);
if (x === null) {
return true;
}
return false;
}
if ( exist() ) {
InfoDataService.create(data)
.then((response) => {
console.log('create', response.data);
setInfo({
id: response.data.id,
sub: response.data.sub,
email: response.data.email,
firstname: response.data.firstname,
lastname: response.data.lastname
});
})
} else {
InfoDataService.update(sub, data)
.then((response) => {
console.log(response.data);
})
.catch((e) => {
console.error(e);
});
}
};
您有两个选项。两者只是相辅相成。
// option 1
if (x) {
return true;
}
return false;
// OR
// option 2
if (!x) {
return false;
}
return true;