I have a javascript (node.js v12) async function that is used to get a resource. It first makes a call to a cache to check if the resource is cached. If it is, then the cached resource is returned. If it is not, then it gets the resource from the path, puts it in the cache, and then returns the resource. The function to put the resource in the cache is async. However, there is no need to wait for this to complete to return the resource. Will it cause any issues if you return from a function while a promise within the function is not yet resolved? I don't even need to know if the function errored because even if the resource can't be put in the cache, I still want to return the resource. Basic example below:
async function getResource(path) {
const cachedResource = await getResourceFromCache(path).catch(logError);
if (cachedResource) {
return cachedResource;
} else {
const resource = await getResourceFromPath(path);
putResourceInCache(path, resource).catch(logError); // This is an async function but I did not use await
return resource;
}
}
app.post('/test', async (req, res) => {
// Code ...
const resource = await getResource(path));
// Code ...
return res.status(200).send(value);
});
If you are not waiting for an asynchronous function to return a value, that's okay and you can still go on with the script.
However, make sure you are handling errors (which you do), so the program will not crash.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With