I had an issue where I needed to return the response of an async function which kept being returned as undefined. So I decided to use setTimeout() before trying to use it. It still doesn’t seem to work. Can someone explain why?
My attempt:
insertUser = (req,res) => {
var record = {
'handle': req.body.handle,
'name': req.body.name,
'password': req.body.password
};
var response;
createUser(record, response)
setTimeout(() => {
console.log(response);
},10000)
};
createUser = (record, response) => {
users.insertOne(record, function(err, result){
if(err){
response = {'code': 404, 'message': 'Something went wrong. Message: ', err}
}else{
response = {'code': 200, 'message': result.insertedId}
}
})
setTimeout(() => {
console.log(response)
}, 1000);
};