I'm just transitioning to async
/await
and have been learning from these resources:
https://javascript.info/async-await
https://medium.com/@rafaelvidaurre/truly-understanding-async-await-491dd580500e
https://hackernoon.com/understanding-async-await-in-javascript-1d81bb079b2c
I think I have understood the main points:
adding
async
before a function definition will ensure any value returned is apromise
adding
await
before the call to theasync
function will "pause" the program until a result is returnedthe function that contains
await
must also have theasync
keyword before its declaration (any 'parent' functions of the container do not require theasync
keyword)the 'await-dependent' declarations should be wrapped in a
try
/catch
block
So I am thinking an ideal async
/await
scenario would look like this:
async function thisWillTakeAges() {
// query a database, fetch external content etc
return desired_value;
}
async function iLoveProgramming() {
try {
var desired_value = await thisWillTakeAges();
} catch (err) {
console.log(err);
return;
}
// do things with 'desired_value' once it has been returned
}
I am trying to incorporate this into an application with the following code:
function get_reset_password_secret(reset_password_user_id) {
// ...
collection.findOne(query, options, async function(err, result) {
if (err) {
res.send(err);
} else {
if (result !== null) {
// ..
return secret;
}
}
});
}
// middleware
const api_resource_get = async (req, res) => {
// ...
try {
var secret = await get_reset_password_secret(reset_password_user_id);
} catch (err) {
console.log("error here at api_resource_get(): " + err);
}
var forgotten_password_token = jwt.sign({ user_email: user_email }, secret);
// ...
}
// route handler
app.route("/api/:api_version/resource")
.get(api_resource_get);
I am getting this error:
(node:14484) UnhandledPromiseRejectionWarning: Error: secretOrPrivateKey must have a value
So there are two issues:
- Why am I getting this error?
- Why is the program stating that the error is unhandled when I do have a
try
/catch
block (which is not console logging the error)?
In regards to the first issue, perhaps it is because get_reset_password_secret()
also needs the async
keyword before it?
In regards to the second issue, I'm not sure why the catch
block is not being recognised.